如何在JS中使用事件监听器

时间:2015-02-15 02:00:30

标签: javascript function button addeventlistener

我试图在程序中使用相同的按钮来实现不同的功能。所以我尝试使用事件监听器但由于某种原因它无法正常工作。可以查看代码并告诉我我做错了什么?谢谢。 (我省略了HTML标签,因此缩短了发布的代码)

    <script type="text/javascript">
    var photo = "photo";
    var edgar = "edgar"

    var x = document.getElementById("yes");
    x.addEventListener("click", choiceyesstory);
    x.addEventListener("click", choiceyesfriendly);

    var y = document.getElementByID("no");
    y.addEventListener("Click", choicenostory);
    y.addEventListener("click", choicenofriendly);

    function choiceyesstory(x) {
    document.getElementById("photo").src = "images/dragon1.jpg";
    document.getElementById("stage1").innerHTML = "Once upon a time";
    setTimeout("choice2()",5*1000);

    }

    function choicenostory(y) {
    document.getElementById("photo").src = "images/sea.jpg";
    document.getElementById("stage1").innerHTML = "Would you like to    
    listen to some music?";
    document.getElementById("edgar").play();
    }
    function choice2(x){
    document.getElementById("photo").src = "images/dragon9.jpg";
    document.getElementById("stage1").innerHTML = "Was he a friendly 
    dragon?";
    }

    function choiceyesfriendly(x) {
    {document.getElementById("photo").src = "images/dragon2.jpg";
    document.getElementById("stage1").innerHTML = "He had many friends";
    }

    function choicenofriendly(y)
    { document.getElementByID ("photo").src = "images/dragon3.jpg";
    document.getElementById("stage1").innerHTML = "He did so and so";
    }


    </script>
    <body>
    <button id="yes">Yes</button>
    <button id="no">No</button>

    </body> 

Edit / Delete Edit Post   Quick reply to this message Reply   Reply With Quote Reply With Quote   Multi-Quote This Message      
  • 回复主题 快速导航DOM和JSON脚本Top 快速回复快速回复

1 个答案:

答案 0 :(得分:0)

我带了你的js并简化了它。事件监听器本身工作正常。也许你在其他地方有问题。

http://jsfiddle.net/jnmav1wk/

var x = document.getElementById("yes");
console.log(x);
x.addEventListener("click", choiceyesstory);

function choiceyesstory(x) {
    alert('Clicked');
}

尝试简化您的问题,摆脱 NO 和所有相应的代码,继续删除代码,直到它正常工作。然后按功能添加功能,直到它停止工作,并且您知道它在哪里被破坏。

我使用 console.log(); alert(); 让我对它更加详细。

有时代码需要在此内部:

$( document ).ready(function() {
  yourCode();
});

这需要jQuery,如果你想避免它,这里有一些选择:

$(document).ready equivalent without jQuery

因为如果函数是针对正在加载的HTML代码执行的(当你尝试将事件监听器附加到它时可能还没有YES按钮等等)