簡體   English   中英

jQuery的點擊事件觸發錯誤的元素?

[英]JQuery click event firing off wrong element?

我有一個問題,其中以下代碼在錯誤的元素上觸發,下面的代碼在名為tag的jQuery小部件的_create函數內部,但是當我單擊下面的gif中的x按鈕時,它刪除了“ “標簽而不是“ yoo”,但是我點擊了“ yoo”

https://gyazo.com/c255d8c136624c235a3af0de4ee40fff

if(this.options.removable)
{

        this.removeButton = $("<span class='close glossy'>x</span>").appendTo(this.element);
        console.log(this.removeButton.parent().text());

        this.removeButton.click(function(e){
            alert(self.element.text());
            self._destroy();

            e.preventDefault();
        });
}

這是生成的html代碼供參考

檢查器中顯示的結果html的圖像

提前致謝。

這是小部件的完整JS代碼

$.widget( "search.tagify", {

options: {
    followerCount: 30,
    description: 

    `a Javascript library, consider also adding the Javascript tag. jQuery is a
     popular cross-browser JavaScript library that facilitates
      Document Object Model (DOM) traversal, 
     event handling…,`,

    name: "tag name goes here",
    removable: false
},

_destroy: function()
{
    //Tips.remove(this.element);
    this.element.remove();
},

_create: function() {
    self = this;

    this.element
        .addClass( "tag" )
        .text( this.options.name )
        .protipSet({
            title: this.options.description,
            position: "bottom",
            size: "small",
            skin: "square",
            classes: "tag-tooltip",
        })

    if(this.options.removable)
    {

        this.removeButton = $("<span class='close glossy'>x</span>").appendTo(this.element);
        console.log(this.removeButton.parent().text());

        this.removeButton.click(function(e){
            alert(self.element.text());
            self._destroy();

            e.preventDefault();
        });
    }

},

});

請檢查以下代碼。

if(this.options.removable)
{

    this.removeButton = $("<span class='close glossy'>x</span>").appendTo(this.element);
    console.log(this.removeButton.parent().text());

    this.removeButton.click(function(e){
        alert(self.element.text());
        //here is the change you can access the targeted element like this as well
        $(e.target).parent('.tag').remove();

        e.preventDefault();
    });
}

我對代碼進行了更改,請檢查,我顯示了選擇目標的其他機制

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM