0

我正在尝试创建一个脚本,每次单击divfurniture时都会使用最后单击的元素更新变量。

不幸的是,虽然这似乎确实有效,但它似乎只是有时有效。就任何类型的一致性而言,我一直找不到任何东西。

$(document).on("click", ".furniture", function() {
    console.log("YouBeClickin'");
    if ( isCurrentElem == 1) {
        $(currentElem).removeClass("chosen")
    }
    currentElem = "#" + this.id; 
    $(currentElem).addClass( "chosen");
    isCurrentElem = 1;
   //alert(currentElem);
});

我正在furniture使用 JavaScript 动态添加我的分类元素,否则我会发布 HTML。在检查 HTML 时,很明显我div的 s 被归类,furniture所以问题不在那里。

点击似乎从未真正触发过,并不是因为我没有在屏幕上得到预期的结果,而是我的控制台中没有记录任何内容。再说一次,这并不是说它永远不会发生,只是它发生得非常罕见。

任何帮助将不胜感激。

4

2 回答 2

0

你可能想要这样的东西:

var currentFurniture; // predefine the "global"

$(document).on("click", ".furniture", function () {
    console.log("YouBeClickin'");
    if ( currentFurniture !== this ) {
        $(currentFurniture).removeClass("chosen");
        currentFurniture = this; 
        $(this).addClass("chosen");
    }
});
于 2013-08-13T20:15:37.713 回答
-1

尝试:

$(document).bind(function() {
    console.log("YouBeClickin'");
    if ( isCurrentElem == 1) {
        $(currentElem).removeClass("chosen")
    }
    currentElem = "#" + this.id; 
    $(currentElem).addClass( "chosen");
    isCurrentElem = 1;
   //alert(currentElem);
});

或使用 Jquery:

$(document).onclick(function() {
    console.log("YouBeClickin'");
    if ( isCurrentElem == 1) {
        $(currentElem).removeClass("chosen")
    }
    currentElem = "#" + this.id; 
    $(currentElem).addClass( "chosen");
    isCurrentElem = 1;
   //alert(currentElem);
});
于 2013-08-13T20:08:04.190 回答