0

我在让我的代码做我想做的事情时遇到了一些麻烦。我有多个部分设置为切换显示/隐藏,并且它运行正常。但是,我现在尝试将图像切换到“更多”而不是始终保持静态的位置,我希望它在扩展时切换到“更少”。

它确实有效......但仅适用于第一个。如果我按下任何其他按钮,它只会改变第一个。您可以在此处查看页面:

http://jfaq.us

我已经尝试了几种不同的变量解决方案,但我似乎无法让它发挥作用。

帮助?提前致谢!


function changeImage() {
    if (document.getElementById("moreorless").src == "http://jfaq.us/more.png") 
    {
        document.getElementById("moreorless").src = "http://jfaq.us/less.png";
    }
    else 
    {
        document.getElementById("moreorless").src = "http://jfaq.us/more.png";
    }
}

function toggleMe(a){
    var e=document.getElementById(a);
    if(!e)return true;
    if(e.style.display=="none")
    {
        e.style.display="block"
    }
    else{
        e.style.display="none"
    }
    return true;
}

<div>

    <a href="http://jfaq.us/guestbook">Guestbook</a>

    <div>

        <input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage();return toggleMe('para3')" >

    </div>

<div id="para3" style="display:none">

This is normally hidden, but shows up upon expanding.
This is normally hidden, but shows up upon expanding.

</div>

    <a href="http://jfaq.us/about">About</a>

    <div>

        <input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage();return toggleMe('para2')" >

    </div>

<div id="para2" style="display:none">

This is normally hidden, but shows up upon expanding.
This is normally hidden, but shows up upon expanding.

</div>

</div>

4

4 回答 4

0

The id attribute must be unique. That's why it's not working. Also, it's not a good idea to use inline event handlers like you are doing, you should register event handlers using addEventListener instead.

Without changing all your code, one thing you can do is pass a reference to the currently clicked element to the changeImage function.

function changeImage(el) {
    var moreUrl = 'http://jfaq.us/more.png';
    el.src = el.src === moreUrl? 'http://jfaq.us/less.png' : moreUrl;
}

Then change the inline handler for onclick="changeImage(this);"

于 2013-08-02T18:30:50.567 回答
0

那是因为您对两个图像使用相同的 id,而 getElementById 显然采用了第一个。

这是更新的代码:html:

 <input type="image" src="http://jfaq.us/more.png" id="moreorless" onclick="changeImage.call(this);return toggleMe('para3')" >

脚本:

// inside the event handler 'this' refers to the element clicked
function changeImage() {
    if (this.src == "http://jfaq.us/more.png") {
        this.src = "http://jfaq.us/less.png";
    } else {
        this.src = "http://jfaq.us/more.png";
    }
}
于 2013-08-02T18:24:46.960 回答
0

您对所有输入使用相同的 ID。这导致了问题。给每个元素一个唯一的 ID。

如果要执行 grp 操作,请使用 jquery 类。

于 2013-08-02T18:28:06.350 回答
0

检查这个

http://jsfiddle.net/Asb5A/3/

function changeImage(ele) {
if (ele.src == "http://jfaq.us/more.png") 
{
    ele.src = "http://jfaq.us/less.png";
}
else 
{
    ele.src = "http://jfaq.us/more.png";
}
}

<input type="image" src="http://jfaq.us/more.png" onclick="changeImage(this);return toggleMe('para3')" >
于 2013-08-02T18:58:03.733 回答