[英]jQuery: How do I add a click handler to a class and find out which element was clicked?
[英]How can I find the element clicked on inside a jquery handler?
如果在jquery的on click方法中傳遞了參數,我試圖對clicked元素執行特定操作。 當我嘗試訪問“ this”時,它引用的是整個窗口,而不是單擊的元素。 我將如何訪問處理程序中的clicked元素?
這是我正在使用的代碼:
var myfunction = function(action) {
var content;
var $this = $(this);
if(action === "one") {
$(".output").text("clicked on one");
$this.addClass("one");
}
if(action === "two") {
$(".output").text("clicked on two");
$this.addClass("two");
}
};
$("#button").on("click", function(event) {
myfunction("one");
});
$("#button2").on("click", function(event) {
myfunction("two");
});
我在這里在jsbin上建立了一個示例。 任何幫助,將不勝感激。
您可以使用Function.prototype.call :
$("#button2").on("click", function(event) {
myfunction.call(this, "two");
});
或將操作作為屬性存儲在元素上,直接綁定處理程序並查詢該屬性。
var myfunction = function() {
var content;
var $this = $(this);
var action = $this.attr('data-action');
if (action === "one") {
$(".output").text("clicked on one");
$this.addClass("one");
} else if (action === "two") {
$(".output").text("clicked on two");
$this.addClass("two");
}
};
$("#button2").on("click", myfunction);
這是指函數所屬的對象,在您的情況下,函數屬於窗口對象或全局對象,根據使用函數的方式,'this'關鍵字的行為會有所不同,例如,如果將其用作構造函數( (使用new關鍵字)'this'將綁定到正在構造的新對象,並且當將該函數用作事件處理程序時,會將其設置為觸發該事件的元素的事件。 有關更多信息,請參見: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this 。
您需要更改代碼並執行以下操作:
$(".button").on("click",function(){
var $this = $(this) //refers to the event it was fired from (button object)
$(".output").text("You clicked on "+$this.text());
});
我使用類而不是ID來定位所單擊的任何按鈕
jsfiddle中的一個示例: http : //jsfiddle.net/fvacbd9u/
有幾種方法可以做到這一點。
JQUERY方式:
在您的jquery click事件處理程序中,您具有event
對象。 它具有一個名為target
的屬性,它就是您要尋找的。
更改此: $this.addClass("one");
為此: $(event.target).addClass("one");
您也可以執行以下操作: event.target.className = "one"
而且顯然也要為“兩個”做...
香草方式:
您只需傳入一個代表您單擊元素的額外參數即可。
var myfunction = function(action, element) {
var content;
if(action === "one") {
$(".output").text("clicked on one");
$(element).addClass("one");
// or event.target.className = "one"
}
if(action === "two") {
$(".output").text("clicked on two");
$(element).addClass("two");
// or event.target.className = "two"
}
};
$("#button").on("click", function(event) {
myfunction("one", this);
});
$("#button2").on("click", function(event) {
myfunction("two", this);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.