2010-04-16 12 views
0

我检查了所有的主题,但我根本不知道为什么我的脚本不能正常工作:(jQuery的addClass的单​​选框选中

<script type="text/javascript"> 
$('input[name=pic]').click(function() {   
    $(this).closest('ul').find(".green").removeClass("green"); 

    if($(this).is(':checked')) { 
     $(this).closest('ul').find("li").addClass('green'); 
    } 
}); 
</script> 

another script what is making the li tags 

var link = document.createElement('li'); 
var parts = result.tbUrl.split('::'); 
link.innerHTML = "<label for='asd"+i+"'><img src='"+result.tbUrl+"' /></label><br /><input id='asd"+i+"' type='radio' name='pic' value='http://"+parts[1]+"' />"; 
contentDiv.appendChild(link); 

etc... 

<ul> 
    <li><input type="radio" name="pic" value="asd"/>asd</li> 
    <li><input type="radio" name="pic" value="b"/>asd</li> 
    <li><input type="radio" name="pic" value="ba"/>asd</li> 
    <li><input type="radio" name="pic" value="bs"/>asd</li> 
    <li><input type="radio" name="pic" value="bc"/>asd</li> 
</ul> 

请帮帮我!

回答

2

$('#pic')是一个ID选择和你的投入没有标识。你可能是指'$('input[name=pic]')

此外,你申请的​​类为<li>,但随后试图找到.green元素里面的.parents('li')。也许你想要$(this).closest('ul')而不是?

+0

仍然没有工作:( - 我纠正了第一后如你所说 – 2010-04-16 11:00:25

+0

工作对我来说,假设正在执行的脚本* *后的'ul'出现在页面(即下面的脚本UL。 ,或者在准备好的文档上运行),你可能也想设置绿色的类只是'$(this).closest('li')'而不是所有的'li'(我不确定你到底是什么'在这里之后) – bobince 2010-04-16 11:11:29

+0

我使用另一个脚本创建了LI元素到ul#内容(称为contentDiv)。 – 2010-04-16 11:21:01

0

bobince是正确的。你需要绑定在一个$(文档).ready

我也使脚本更高效。

<script type="text/javascript"> 
    $(document).ready(function() { 
     $(':radio[name=pic]').click(function() {   
      $(this).siblings().removeClass("green").end() 
      .addClass("green"); //a click always makes a radio button true, so no need to check 
     }); 
    }); 
</script>