【问题标题】:why doesn't my jquery click function work after changing element values?为什么我的 jquery click 函数在更改元素值后不起作用?
【发布时间】:2016-01-29 01:55:10
【问题描述】:

所以我正在使用 Object.create 克隆方法使用面向对象的 JS 制作一个小测验应用程序。我有一个 ol 和一个名为 showVals() 的函数,它用 lis 填充它。这似乎工作正常。我遇到的问题是:我的 li click 函数赋予“.selected”类的属性似乎最初可以工作,但是在我点击继续并调用 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";

【问题讨论】:

  • 这是因为你的 click 事件是在你的 DOM 元素改变之前绑定的,你可以在每次改变你的 DOM 时绑定事件或者在你的 li 标签中使用 onclick 属性
  • 非常感谢。我很感激。

标签: javascript jquery oop


【解决方案1】:

这可能是因为您的li 元素是动态添加的。 您应该尝试使用jQuery on(),它允许您将事件处理程序绑定到您的 DOM 中必须已经存在的父元素,然后您可以指定将调用事件处理程序的子/后代选择器。在您执行事件绑定时,此子元素可能仍然不存在。在这种情况下,您可以像这样调用 on():

$('ol').on('click', 'li', function () {...});

ol 已经存在。

或者,在将点击处理程序添加到 DOM 后,您始终可以将它们绑定到动态生成的 li 元素。尽管我认为这会耗费更多的处理器时间,因为我假设您必须对您向用户提出的所有测验问题执行此操作。

【讨论】:

  • 这有帮助。非常感谢。
猜你喜欢
  • 2022-12-08
  • 2014-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多