我有一个问题,其中以下代码在错误的元素上触发,下面的代码在名为tag的jQuery小部件的_create函数内,但是当我单击下面gif中的x按钮时,它将删除“ goo”标签而不是“ 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代码供参考
image of resulting html as displayed in the inspector
谢谢。
这是小部件的完整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();
});
}
},
});
答案 0 :(得分:-1)
请检查以下代码。
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();
});
}
我对代码进行了更改,请检查,我显示了选择目标的另一种机制