Jquery/Javascript目标函数

Jquery/Javascript target in function

本文关键字:函数 目标 Javascript Jquery      更新时间:2023-09-26

我有一个函数,我调用两个图像,像这样。

$('#image1').bind('click',doNext);
$('#image2').bind('click',doNext);

我需要知道是哪一个调用了函数

function doNext(){
if(target == $('#image1'){
   alert('image1');
     }else{
   alert('image2');
    }
}

doNext中的this将是原始DOM元素,因此:

function doNext() {
   if (this.id === "image1") {
       alert('image1');
   }else{
       alert('image2');
   }
}

这里我在id上进行了分支,因为您在代码中特别这样做了,但通常您只是与对象进行交互。

如果您需要使用任何jQuery函数,将原始DOM元素包装在jQuery对象(var $this = $(this);)中,但如果您想做的只是像我上面所做的那样查看id,则不需要这样做。

在jQuery事件处理程序中,(至少)有两个重要的DOM元素可以访问:钩住事件的元素(this)和触发事件的元素(event.target)。在您的情况下,假设image1image2img元素,它们将是相同的,因为img不能包含任何其他元素,但在元素可以包含其他元素的情况下(div, p等)。例如,大多数元素),event.target可能不同于this。假设你有:
<div id="foo">
   <p>Blah blah blah</p>
</div>

$("#foo").click(function(event) {
    alert(this.tagName);
    alert(event.target.tagName);
});

如果你点击这个段落,你会得到

<>以前DIVP 之前

…因为你在div上钩住了事件,但它是由点击p触发的。(这是事件委托的基础)

var id = $(this).attr('id');
if (id == 'image1') {
   alert('image1');
} else{
   alert('image2');
}

使用attr()函数检索元素的ID。此外,我还将通过向两个图像添加一个公共类来进一步简化此操作,以便您可以这样做:

$('.myimages').click(function() {
    if($(this).attr() == 'image1') {
       alert('image1');
    } 
    else {
       alert('image2');
    }
});

您可以使用event.target:

function doNext(event){
if($(event.target).attr('id') == 'image1'){
   alert('image1');
     }else{
   alert('image2');
    }
}

您可以在事件处理函数中获得event.target:

function doNext(event) {
    var target = event.target;
}

或者,this将指向被单击的元素:

function doNext() {
    var clickedID = this.id;
}
$(document).ready(function() {
$('#image1').click(function(){doNext('image1')});
$('#image2').click(function(){doNext('image2')});
});
doNext = function (target){
if(target == "image1"){
   alert('image1');
     }else{
   alert('image2');
    }
}