根据Jquery中相同标记的所有值更改按钮文本
我有以下HTML代码根据Jquery中相同标记的所有值更改按钮文本,jquery,html,Jquery,Html,我有以下HTML代码 <i>0</i> <i>0</i> <i>0</i> <button>Test</button> 我所有的标记值仍然为0,但我看不到按钮文本的变化通过每个i元素循环,检查它的内容是否为0,如果是,并且c==3(这意味着有3个零)更改按钮元素的文本 var c = 0; $('i').each(function () { if ($(this).html() == '0
<i>0</i>
<i>0</i>
<i>0</i>
<button>Test</button>
我所有的
标记值仍然为0,但我看不到按钮文本的变化通过每个i
元素循环,检查它的内容是否为0
,如果是,并且c==3
(这意味着有3个零)更改按钮
元素的文本
var c = 0;
$('i').each(function () {
if ($(this).html() == '0') {
c++;
if (c == 3) {
$('button').text('Test2');
}
})
或者您可以尝试以下简化代码:
if ($('i').text() == '000') {
$('button').text('Text2');
}
实际上,由于性能原因,您不应该遍历整个
数组。您应该使用
返回false当第一个非0
值出现时,用于停止循环的.each()
处理程序的内部
$(document).click(function(){
var change = true;
$('i').each(function() {
if ($(this).text() != '0') {
change = false;
return false;
}
});
if (change)
$('button').text('Test2');
});
您只需要:
$('button').on('click', function (e) {
// preventing the default action of the button:
e.preventDefault();
$(this).text(function () {
// caching the collection of <i> elements:
var iEls = $('i');
// comparing the number of <i> elements whose text is '0'
// against the number of <i> elements, returning a Boolean;
// if the Boolean is true we return 'text2', if false 'text':
return iEls.filter(function () {
return $(this).text().trim() === '0';
}).length === iEls.length ? 'text2' : 'text';
});
});
0
0
0
测试
不符合预期。按钮的文本取决于
@user3667167的最后一个值-我很困惑,您期望的是什么?如果所有的值都是0,那么将按钮文本更改为test2实际上您不应该遍历所有的数组!不像预期的那样jsfiddle.net/hrpLkLva/2按钮的文本取决于
的最后一个值,但我想检查是否有任何值不是零,如果有任何值是0。您的意思是,要更改按钮的文本,所有值都应为0@用户3667167请在此处再次解释@用户3667167
$('button').on('click', function (e) {
// preventing the default action of the button:
e.preventDefault();
$(this).text(function () {
// caching the collection of <i> elements:
var iEls = $('i');
// comparing the number of <i> elements whose text is '0'
// against the number of <i> elements, returning a Boolean;
// if the Boolean is true we return 'text2', if false 'text':
return iEls.filter(function () {
return $(this).text().trim() === '0';
}).length === iEls.length ? 'text2' : 'text';
});
});