<div class="test-test-one">one</div>
<input type="checkbox" class="now" name="here_one"> <br />
<div class="test-test-two">two</div>
<input type="checkbox" class="now" name="here_two"> <br />
<div class="test-test-three">three</div>
<input type="checkbox" class="now" name="here_three"> <br />
<div class="test-test-four">four</div>
<input type="checkbox" class="now" name="here_four"> <br />
小提琴:http://jsfiddle.net/3eUEp/
我想做:
如果我单击名称 = here_one 的复选框,那么这应该是将类 .red 添加到带有类测试一的div如果我单击带有类测试测试一的div,那么也应该选中名称 = here_one 的复选框。
我怎样才能用jQuery做到这一点? 我不想使用上一个和下一个。我想使用选择器,但是如何使用 PHP 的 substr?
http://www.w3schools.com/jsref/> 这是javascript文档:
和jQuery:http://docs.jquery.com/Main_Page
$('.now').click(function(){
var v = $(this).attr('name').replace('here_', '');
if($(this).is(':checked'))
{
$('.test-test-'+v).addClass('red');
}
else
{
$('.test-test-'+v).removeClass('red');
}
});
$("div[class^='test-test']").click(function(){
if($(this).hasClass('red'))
{
$(this).next('.now').attr('checked', false);
$(this).removeClass('red');
}
else
{
$(this).next('.now').attr('checked', true);
$(this).addClass('red');
}
});
$('.now').click(function(){
var elem = $(this); //the checkbox
var numStr = elem.prop("name").split("_")[1]; //split the name into pieces
$(".test-test-" + numStr).toggleClass("red", elem.is(":checked")); //get the element, toggle the class
});
编辑的jsfiddle
现在你不应该使用div,你应该使用标签。单击标签将执行您想要的操作。不需要JavaScript。
<label class="test-test-one" for="foo1">one</div>
<input type="checkbox" class="now" name="here_one" id="foo1"> <br />
当您使用标签时,您正在为人们提供使用屏幕阅读器的服务。
你不需要任何PHP,JS本身有一个substr
方法。
$(function() {
$("input.now").change(function(e) {
var div = $("div.test-test-"+this.name.substr(5));
if (this.checked)
div.addClass("red");
else
div.removeClass("red");
});
});
(jsfiddle.net 演示)
$("div[class^=test-test-]").click(
function ()
{
var sub = ($(this).attr("class")).substring(10);
$(".now[name=here_"+sub+"]").attr("checked",true);
}
);
$(".now").click(
function ()
{
var sub = ($(this).attr("name")).substring(5);
alert(sub);
$(".test-test-"+sub).addClass("red");
}
);
$('.now').click(function(){
var name_part = $(this).prop('name').split('_')[1];
if($(this).is(':checked')){
$('div[class$='+name_part+']').css('color', '#F00');
}else{
$('div[class$='+name_part+']').css('color', '#000');
}
});