0
<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添加到带有类test-test-one 的 div 中,如果我单击带有类test-test-one 的div 那么也应该选中带有名称 = here_one的复选框。

我怎样才能用 jQuery 做到这一点?我不想使用 prev 和 next。我想使用选择器,但是如何使用 PHP 中的 substr 呢?

4

5 回答 5

1
$('.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
});

Edited jsfiddle

Now you shoudl not be using divs, you should be using labels. Clicking on a label will do what you want. There is no JavaScript needed.

<label class="test-test-one" for="foo1">one</div>
<input type="checkbox" class="now" name="here_one" id="foo1"> <br />

And when you use a label, you are doing people a service that are using screen readers.

于 2012-08-17T14:55:08.743 回答
1

这是 javascript 文档:http ://www.w3schools.com/jsref/

和 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');
    }
});
于 2012-08-17T14:55:53.617 回答
0
$("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");
    }
    );
​
于 2012-08-17T14:57:02.977 回答
0
$('.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');  

  }
});
于 2012-08-17T15:00:28.783 回答
0

你不需要任何 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 上的演示

于 2012-08-17T14:56:22.070 回答