0

在下面链接的小提琴中,有一些我需要排除故障的示例代码。为了在小提琴中进行演示,我已经从原始代码(没有编写)中对其进行了一些简化。

$(document).ready(function(){
    $("ul").children().each(function(i){
        $(this).click(function(){
            var indexItem = i; 

            if(indexItem == 0){
                 displayId();                                  
            }
            if(indexItem == 1){
                displayNode();
            }
            if(indexItem == 2){
                displayNodevalue();
            }
       });
    });
})
function displayId(event){
   // below returns undefined not what I want
   // var $listID = jQuery(this).attr("id"); 
   var $listID = event.target.id;
    alert($listID);
}

function displayNode(event){
    var listNodename = event.target.nodeName;
    alert(listNodename);
}

function displayNodevalue(event){
    var listValue = event.target.nodeValue;
    alert(listValue);
}

如何获取这些项目的 event.target 属性?控制台显示:

Uncaught TypeError: Cannot read property 'target' of undefined

我在下面搜索了各种可能的解决方案。他们很好,但我没有找到答案。

如何将事件对象传递给命名函数

获取触发事件的元素的 ID

https://api.jquery.com/event.target/

如果我错过了这些线程中的答案,请告诉我。似乎这个问题应该在某个地方得到回答,但我很难找到它。如果没有,我会很感激一些帮助,告诉我这段代码有什么问题以及如何获取事件目标。谢谢。

小提琴链接

4

3 回答 3

3

首先,each()是冗余代码,因为您可以使用 访问被index点击元素的$(this).index()。然后您只需要捕获在单击处理程序中引发的事件并将其传递给您的其他函数。试试这个:

$(document).ready(function () {
    $("ul").children().click(function (e) {
        var indexItem = $(this).index();

        if (indexItem == 0) {
            displayId(e);
        }
        if (indexItem == 1) {
            displayNode(e);
        }
        if (indexItem == 2) {
            displayNodevalue(e);
        }
    });
})

function displayId(e) {
    var $listID = e.target.id;
    alert($listID);
}

function displayNode(e) {
    var listNodename = e.target.nodeName;
    alert(listNodename);
}

function displayNodevalue(e) {
    var listValue = e.target.nodeValue;
    alert(listValue);
}

更新的小提琴

于 2015-04-01T06:43:11.160 回答
2

您需要将事件对象作为参数传递

$(document).ready(function () {
    $("ul").children().each(function (i) {
        $(this).click(function (e) {
            var indexItem = i;

            if (indexItem == 0) {
                displayId(e);
            }
            if (indexItem == 1) {
                displayNode(e);
            }
            if (indexItem == 2) {
                displayNodevalue();
            }
        });
    });
})

演示:小提琴


也试试

$(document).ready(function () {
    var fns = [displayId, displayNode, displayNodevalue]
    $("ul").children().click(function (e) {
        var indexItem = $(this).index();
        fns[indexItem] ? fns[indexItem](e) : '';
    });
})

演示:小提琴

于 2015-04-01T06:40:57.503 回答
1

将 click 函数中的事件参数传递给您的函数,如下所示:

$(this).click(function (event) {
   var indexItem = i;
   if (indexItem == 0) {
     displayId(event);
   }
   if (indexItem == 1) {
     displayNode(event);
   }
   if (indexItem == 2) {
     displayNodevalue();
   }
});
于 2015-04-01T06:43:51.633 回答