我的问题是正确切换一些按钮的状态。我使用jquery单击事件。但是我不知道问题出在哪里,也不想不小心错过了。我寻找类似的问题,但似乎没有解决我的问题。
我开始呈现一个div,其中包含了我今天想要做的一些任务。我想让他们不管做了还是不做。
{
$('#currentDiv').hide();
rewriteDivFromScratch();
$('#eachday').show();
}其中,rewriteDivFromScratch将按钮div添加到HTML中。
<div id="eachday"> .. </div>
<div id="button-0" class="button"> <button class="btn btn-mini"> .. </button> </div>
..
<div id="button-7" class="button"> <button class="btn btn-mini"> .. </button> </div>function rewriteDivFromScratch() {
el = $("#eachday");
// get the HTML divs from Handlebars templating compilation
// they're OK, I checked with inspector
// This renderes nicely, no problem here.
el.html(html);
}我为按钮添加了一个单击事件,以便与上面的按钮在同一个文件中切换:
$('.btn-mini').click( function(e) {
e.preventDefault();
var el = $(e.currentTarget); // the <button />
el.toggleClass('btn-inverse');
}我得到了没有切换效应..。
现在,我想这是因为在$(.)执行时还没有..btn mini类。这就是为什么我添加了一个像这样的setInterval:
var intervalId; // it's global in my js file
function rewriteDivFromScratch() {
...
// This renderes nicely, no problem here.
el.html(html);
intervalId = setInterval(check); // this fires only once, so seems OK
}var check = function() {
$('.btn-mini').click( function(e) {
e.preventDefault();
var el = $(e.currentTarget); // the <button />
if (el.length)
clearInterval(intervalId);
else
return;
// It executes this toggle more than **15** times per
// click on button.. Now, why is that?
el.toggleClass('btn-inverse');
}
};正如我在上面的注释中所说的,我的问题是这个部分被多次执行,而不是每次刷新的固定次数,以便找到一个模式或其他东西。
上面的js代码位于一个“app.js”中,与其他脚本一样,我只是将其包含在index.html中。
发布于 2012-06-24 11:36:04
只需对“委托事件”使用jquery的“live”,每当在文档中插入新按钮时,jquery也会工作:
$('.button').live('click', function(){
//button clicked
});有关“live”如何工作的进一步说明,请参见http://api.jquery.com/live/。
https://stackoverflow.com/questions/11177036
复制相似问题