如果选中此复选框,则对其邻居执行此操作

时间:2013-11-11 17:17:20

标签: javascript jquery checkbox observable

我忽略了一些非常基本的东西。我想在点击一个复选框时为组中的特定元素着色。所以我需要观察这些元素。

这就是我的html看起来像

<p>
    <label>
        <i>bla2</i>
        <input type="checkbox" />
    </label>
</p>

<p>
    <label>
        <i>bla3</i>
        <input type="checkbox" />
    </label>
</p>

我的JS看起来像这样

$(document).ready(function() {

    function handleCheckbox () { 

        if ( $(this).closest(':checkbox').is(':checked') ) {
            $('this').closest('i').css('color','green');
        } else {
            $('this').closest('i').css('color','red');
        }
    }

    handleCheckbox();
    $('label').on('click', handleCheckbox() );

 });

3 个答案:

答案 0 :(得分:1)

您正在传递函数而不是使用匿名函数,因此请删除()

$('label').on('click', handleCheckbox);

否则这将在页面加载时立即执行。另外,取消引用this

$(this).closest('i').css('color','green');

答案 1 :(得分:1)

.closest()查看当前元素,然后查看祖先的层次结构,而不是邻居。在您的情况下,this会指向标签对象,以便您可以查看子项以查找<i>标记和<input>标记。您还有其他几个编码错误。

此外,您的handleCheckbox()函数需要将this的值设置为<label>对象才能正常工作,因此您无法直接调用它并期望将其设置为全部适当的颜色。相反,您必须遍历页面中的所有标签,并为每个标签调用handleCheckbox()。我已使用.each()在下面的代码中完成了这项工作。

这是解决问题的方法:

$(document).ready(function() {
    function handleCheckbox() {
        // the this pointer here will point to the label object so you need
        // can use .find() to find children of the label object
        var newColor;
        if ($(this).find("input").is(":checked")) {
            newColor = "green";
        } else {
            newColor = "red";
        }
        $(this).find("i").css("color", newColor);
    }
    // hook up click handler and initialize the color for all labels
    $('label').on('click', handleCheckbox).each(handleCheckbox);        

 });

参见工作演示:http://jsfiddle.net/jfriend00/tRQ99/并注意到初始颜色也是根据初始复选框状态设置的。

您的代码存在以下问题:

  1. .closest()走向祖先。它找不到邻居。
  2. 传递回调函数时,最后不要使用(),因为这会导致它立即执行并传递执行函数的返回值。你只想传递一个没有parens的函数的引用。
  3. 您没有引用this。将其视为javascript变量,而不是字符串。
  4. this指针将指向回调中的标签对象,因此您需要查看子元素以查找<i><input>对象。您可以使用.children().find()来查找它们。
  5. handleCheckbox()的初始调用无法正常工作,因为仅当this设置为<label>对象(它在事件处理程序中的工作方式)时才有效。因此,要使用与事件处理程序相同的初始化函数,您需要迭代所有标签并确保为该函数正确设置this。一个简单的方法是使用.each(),就像我在代码建议中所示。

答案 2 :(得分:0)

在这里你可能想要的东西小提琴:

http://jsfiddle.net/93CeR/2

$(document).ready(function() {

    function handleCheckbox () { 

        if ( $(this).find(':checkbox').is(':checked') ) { // Use .find instead of closest because the element you want is a child
            $(this).find('i').css('color','green'); // Remove qoutes from this and use .find for same reason as above
        } else {
            $(this).find('i').css('color','red'); // Ditto
        }
    }

    $('label').each(function(){
       handleCheckbox.apply(this); // We need to call the function initially using 'label' for this.
    });
    $('label').on('click', handleCheckbox ); // You want a reference to handleCheckbox not to invoke it so remove the parenthesis

 });
相关问题