2014-03-18 34 views
0

我的HTML是这样的:Javascript来添加一个标签上的CSS类

<table class="ListCheck"> 
<tbody> 
<tr> 
<td> 
<span class="listitem"> 
    <input name="ctl00$MainContent$List$0" class="location" id="MainContent_List_0" type="checkbox"> 
    <label for="MainContent_List_0">test</label></span> 
</td> 
<td> 
<span class="listitem"> 
    <input name="ctl00$MainContent$List$1" class="location" id="MainContent_List_1" type="checkbox"> 
    <label for="MainContent_List_1">test</label></span> 
</td> 
<td> 
<span class="listitem"> 
    <input name="ctl00$MainContent$List$2" class="location" id="MainContent_List_2" type="checkbox"> 
    <label for="MainContent_List_2">test</label></span> 
</td> 
</tr> 
</tbody> 
</table> 

我试图添加JavaScript添加标签上的一类应用一些CSS当复选框被选中

我脚本是:

<script type='text/javascript'> 
     $('.listitem').each(function() { 
      $(this).children("input").addClass("location"); 
      if ($(this).children("input").is(":checked")) 
      { 
       $(this).children('label').addClass("checked"); 
      } else { 
       $(this).children('label').removeClass("checked"); 
      } 
     }); 
</script> 

但由于某种原因,它没有在运行时在标签上添加类。请看我的代码,让我知道我缺少什么。 TIA。

+0

多数民众赞成在jquery哟,没有必要混合纯js,你是什么意思,在运行时,你的意思是当你真的去检查一些东西或你有预先检查页面加载的东西?你需要一些事件处理的第一个。 – Rooster

+1

您错过了结束标签和输入标签。请验证它没有出现在真实代码中 – Unnie

+0

您是否在元素被添加到页面之前调用它? – epascarello

回答

4

可以使用next()方法来访问相应<label>如下:

$('input[type="checkbox"]').click(function() { 
    $(this).next().toggleClass("checked"); 
}); 

Working fiddle

+0

我需要将css类添加到标签中,而不是添加到标签的输入字段 – svs

+0

@svg。检查小提琴 –

1

尝试使用你的代码

$(".target").change(function() { 
     alert("Handler for .change() called."); 
    }); 

所以

<script type='text/javascript'> 
     $('.listitem').each(function() { 
      $(this).children("input").addClass("location"); 

      $(this).children("input").change(function() { 

      if ($(this).children("input").is(":checked")) 
      { 
       $(this).children('label').addClass("checked"); 
      } else { 
       $(this).children('label').removeClass("checked"); 
      } 
      });// missing bracket ;) 
     }); 
</script> 
0

我改变了一下你的代码,如果我理解你的话是错误的。

$('.location').click(function() { 
       if ($(this).is(":checked")) 
       { 
        console.log('added'); 
        $(this).closest('label').addClass("checked"); 
       } else { 
        console.log('removed'); 
        $(this).closest('label').removeClass("checked"); 
       } 
    }); 

http://jsfiddle.net/W7nr4/

0

JavaScript代码应该是这样的:

$('.listitem').click(function() { 
     $(this).children("input").addClass("location"); 
     if ($(this).children("input").is(":checked")) 
     { 
      $(this).children('label').addClass("checked"); 
     } else { 
      $(this).children('label').removeClass("checked"); 
     } 
    }); 

点击应用到由选择中找到的所有元素。

相关问题