我如何做 foreach
或类似的 jQuery?当用户点击 <span>
时我需要它, 添加类 inactive
所有 <div>
s 与 vote active
<ul>
中的类.
我试过 .each
方法,但它不起作用。
我有这个 HTML:
<ul class="suggestions inactive">
<li id="s2">
<div class="id">2</div>
<div class="vote inactive">
<span class="up"></span>
<span class="down"></span>
</div>
<div class="text">test2</div>
<div class="rating">2</div>
</li>
<li id="s3">
<div class="id">3</div>
<div class="vote active">
<span class="up"></span>
<span class="down"></span>
</div>
<div class="text">test3</div>
<div class="rating">0</div>
</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="script.js"></script>
还有这个脚本:
$(document).ready(function(){
var ul = $('ul.suggestions');
// Listening of a click on a UP or DOWN arrow:
$('div.vote span').live('click',function(){
var elem = $(this),
parent = elem.parent(),
li = elem.closest('li'),
ratingDiv = li.find('.rating'),
id = li.attr('id').replace('s',''),
v = 1,
ul2 = elem.closest('li').parent();
// If the user's already voted:
if(parent.hasClass('inactive')){
return false;
}
if(ul2.hasClass('inactive')){
return false;
}
//If the user's already voted, add following class
parent.removeClass('active').addClass('inactive');
ul2.removeClass('active').addClass('inactive');
if(elem.hasClass('down')){
v = -1;
}
// Incrementing the counter on the right:
ratingDiv.text(v + +ratingDiv.text());
// Turning all the LI elements into an array
// and sorting it on the number of votes:
var arr = $.makeArray(ul.find('li')).sort(function(l,r){
return +$('.rating',r).text() - +$('.rating',l).text();
});
// Adding the sorted LIs to the UL
ul.html(arr);
// Sending an AJAX request
$.get('ajax.php',{action:'vote',vote:v,'id':id});
});
最佳答案
这里根本不需要.each()
。
为什么?因为 jQuery 的选择器可以完美地选择单一选择器类型的所有内容。 $('p')
选择 HTML 中的 every p
。
你应该使用
$(this).parent().addClass('active').removeClass('inactive');`
从范围内
$('div.vote span').live('click',function() { ... } );
此外,请记住 .live()
在 jQuery 1.7+ 中已弃用。
关于php - jQuery,在 ul 中 foreach div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8662938/