这比我预期的要困难得多。我试图使用jquery选择器编写if / else语句..我想根据点击的无线电来附加消息。我的逻辑工作正常,但是当单击某个单选按钮时,我无法输出消息。我可以轻松地同时打印两个结果,但无法根据所选的无线电来弄清楚如何打印单独的响应。
这是我的功能:
function imageCounter() {
var ballCount = 0;
var truckCount = 0;
// find images with ball in image src
$('img[src*=ball]').each(function() {
if($(this).attr('src')) {
ballCount+=1;
}
});
// find images with truck in image src
$('img[src*=truck]').each(function() {
if($(this).attr('src')) {
truckCount+=1;
}
});
if($(':radio[name="truckImages"]:checked')) {
$('#radioButtons').append("There are " + truckCount + " truck images.");
} else {
$('#radioButtons').append("There are " + ballCount + " ball images.");
}
}
HTML:
<div id="radioButtons">
<input type="radio" value="truckImages" name="truckImages" id="truckImages">Fire Trucks
<input type="radio" value="ballImages" name="ballImages" id="ballImages">
<input type="button" value="Count the Images" onclick="imageCounter()">
</div>
答案 0 :(得分:0)
我认为问题是$ .fn会返回与查询匹配的元素数组。如果没有任何元素匹配,if将返回一个空数组。在JavaScript中,!![]
会返回true
。在这里,您应该使用.length
if($(':radio[name="truckImages"]:checked').length) {
$('#radioButtons').append("There are " + truckCount + " truck images.");
} else {
$('#radioButtons').append("There are " + ballCount + " ball images.");
}
或
if($(':radio[name="truckImages"]').is(':checked')) {
$('#radioButtons').append("There are " + truckCount + " truck images.");
} else {
$('#radioButtons').append("There are " + ballCount + " ball images.");
}
实际上,我认为你不需要调用$('img')的每个函数。
function imageCount() {
var type = $(':radio:checked')).attr('name').replace(/Images$/, '');
var count = $('img[src*=' + type + ']').length;
$('#radioButtons').after("There are " + count + " " + type + " images.");
}