Javascript 单击可在长列表中的两个图像之间切换

Javascript 单击可在长列表中的两个图像之间切换,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个很长的列表(动态创建),它只能包含两个图像中的一个;red.png或green.png,如下所示: <img src="red.img" id="choice1" onclick=" changeIcon('1')"> <img src="red.img" id="choice2" onclick=" changeIcon('2')"> ... <img src="red.img" id="choiceN" onclick=" changeIcon('N')

我有一个很长的列表(动态创建),它只能包含两个图像中的一个;red.png或green.png,如下所示:

<img src="red.img" id="choice1" onclick=" changeIcon('1')">
<img src="red.img" id="choice2" onclick=" changeIcon('2')">
...
<img src="red.img" id="choiceN" onclick=" changeIcon('N')">
我试图做的是,当我点击红色图像时,只有这个(id?)变为绿色,列表的其余部分变为红色,如果我点击绿色,那么它会变回红色,所以整个列表再次变为红色。
该概念类似于单选按钮,但不使用表单一次更改所有项目,而是将类添加到图像中(我将使用名为
img
的类作为示例):


(注意,您需要直接查看图像的src以查看更改)

只需使用class属性将整个列表更改为红色,然后切换单击的项目

    //the jQuery function
    function toggleSrc()
    {
        var nextSrc = "red.png";

        if( $(this).attr("src") == "red.png" )
            nextSrc = "green.png";

        $(".image").attr("src","red.jpg");
        $(this).attr("src",nextSrc);
    }

    //binding function to .image
    $( document ).ready(function() {
        $(".image").click( toggleSrc );
    });

    //and the HTML:
    <img src="red.png" class="image" id="choice1">
    <img src="red.png" class="image" id="choice2">
//jQuery函数
函数toggleSrc()
{
var nextSrc=“red.png”;
if($(this.attr(“src”)==“red.png”)
nextSrc=“green.png”;
$(“.image”).attr(“src”、“red.jpg”);
$(this.attr(“src”,nextSrc);
}
//将函数绑定到.image
$(文档).ready(函数(){
$(“.image”)。单击(toggleSrc);
});
//以及HTML:
好吧,尝试使用:

var l = "choice" + line;
或者,更好的是,我建议您使用jQuery以这种方式更改代码:

$(函数(){
//将“body”替换为“img.toggle”的某个静态父级。
$(“body”)。在(“单击”,“切换”,函数(){
if($(this.attr(“src”)=“red.img”)
this.src=“green.img”;
其他的
this.src=“red.img”;
});
});


这只会将单个项目切换为绿色,列表的其余部分也会更改。@SpencerWieczorek它只会更改单击的图像。确切地说:“此(id?)变为绿色,列表的其余部分变为红色”最后一点是,在第二个代码段中,您需要检查单击的项目是否为
红色.png
。呃,但这和我的回答几乎一样。也许没有必要让OP去了解该做什么的概念。@SpencerWieczorek是的,让我们等待OP的回应<代码>:)
$(".img").click(function(){
    if( $(this).attr('src') == "red.png" ) {
        $(".img").attr('src', "red.png"); // Make them all red
        $(this).attr('src', "green.png"); // Change the clicked one to green
    }
});
    //the jQuery function
    function toggleSrc()
    {
        var nextSrc = "red.png";

        if( $(this).attr("src") == "red.png" )
            nextSrc = "green.png";

        $(".image").attr("src","red.jpg");
        $(this).attr("src",nextSrc);
    }

    //binding function to .image
    $( document ).ready(function() {
        $(".image").click( toggleSrc );
    });

    //and the HTML:
    <img src="red.png" class="image" id="choice1">
    <img src="red.png" class="image" id="choice2">
var l = "choice" + line;