[英]why doesn't my jquery click function work after changing element values?
因此,我使用Object.create克隆方法使用面向對象的JS制作了一個小型測驗應用程序。 我有一個ol,還有一個名為showVals()的函數,它使用lis填充它。 這似乎很好。 我遇到的麻煩是:我的li click函數提供了“ .selected”類的attr屬性,雖然看起來確實是在起作用,但是在我單擊繼續並調用qn2.showVals()之后,它不再給lis單擊時選擇的類別。
qn2的數據在那里。 一切看起來正常,除了單擊功能不再起作用(為lis提供類)。
$(document).ready(function(){
qn1.showVals();
qn1.setAns(1); // calling question1 answer for now
$('li').click(function(){
$('li').removeAttr("class");
$(this).attr({"class": "selected"});
});
$('.proceed').click(function(e){
e.preventDefault();
if ($('.selected').html() == qn1.ctAns) {
if (confirm("You are correct")){
qn2.showVals();
qn2.setAns(3);
};
};
});
});
var qn1 = {
title:"The Mouth of Sauron",
qn: "How did 'The mouth of Sauron' meet his demise?",
img: "images/mouth-sauron.gif",
ans: ["Shot in the back", "Beheaded", "Drowned in a swamp", "Sacrificed"],
setAns: function(x) {
this.ctAns = this.ans[x]; //setting correct answer
},
showVals: function(){
$('#slide-title').text(this.title);
$('.question-box > p').text(this.qn);
$('#obj-img').attr("src", this.img);
$('ol').html('<li>'+this.ans[0]+'</li>'+'<li>'+this.ans[1]+'</li>'+
'<li>'+this.ans[2]+'</li>'+'<li>'+this.ans[3]+'</li>')
}
}
var qn2 = Object.create(qn1);
qn2.title = "Golemn";
qn2.qn = "What this dude's name?";
qn2.ans= ["Golemn", "Gimli", "Goober", "Poop"]
qn2.img = "images/golemn.gif";
這可能是因為您的li
元素是動態添加的。 您應該嘗試使用jQuery on() ,它允許您將事件處理程序綁定到DOM中必須已經存在的父元素,然后可以指定將調用事件處理程序的子/后代選擇器。 在進行事件綁定時,此子元素可能仍然不存在。 在這種情況下,您可以像這樣調用on():
$('ol').on('click', 'li', function () {...});
ol
已經存在的地方。
另外,在將點擊處理程序添加到DOM之后,也可以始終將其單擊處理程序綁定到動態生成的li
元素。 盡管我認為這會消耗更多的處理器時間,因為我認為您必須對詢問用戶的所有測驗問題進行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.