有没有更好(更明智)的方法来实现同样的目标

Is there a better (more sensible) way to achieve this same goal?

本文关键字:方法 实现 目标 更好 有没有      更新时间:2023-09-26

我对以前的问题有一个有效的解决方案,但它不像是好的程序员习惯。有更好的解决方案吗?还是这只是一条路?

这是我的HTML:

<ul>
    <li onclick="answerswer(this)">A</li>
    <li onclick="answerswer(this)">B</li>
    <li onclick="answerswer(this)">C</li>
    <li onclick="answerswer(this)">D</li>
</ul>

还有我的JS:

window.answer = function (elm) {
    if ($(elm).is(':nth-of-type(1)')) {
        alert('elm is 1st of type');
    } else if ($(elm).is(':nth-of-type(2)')) {
        alert('elm is 2nd of type');
    } else if ($(elm).is(':nth-of-type(3)')) {
        alert('elm is 3rd of type');
    } else if ($(elm).is(':nth-of-type(4)')) {
        alert('elm is 4th of type');
    }
};

这个代码的作用是,它提醒第n个子(对于第2个<li>,它提醒elm is 2nd of type(

简而言之,有没有更好(更合乎逻辑(的方法来实现同样的结果?如果是这样,我应该如何实现呢?

干杯!

由于您使用JQuery,您可能会发现使用index函数的实用程序:

https://api.jquery.com/index/

在您的回答函数中,您可以为所有想要匹配的li添加一个选择器(例如,如果您有多个无序列表(,然后:

var zeroBasedIndex = $("your-li-selector").index(elm);

请记住,这将返回一个基于零的位置,请随时向++查找您的位置。

希望这能帮助

<ul>
    <li data-type="1st" onclick="answerswer(this)">A</li>
    <li data-type="2nd" onclick="answerswer(this)">B</li>
    <li data-type="3rd" onclick="answerswer(this)">C</li>
    <li data-type="4th" onclick="answerswer(this)">D</li>
</ul>

脚本

window.answer = function (elm) {
    var type = $(elm).attr("data-type");
    var message = 'elm is ' + type + ' of type';
    alert(message);
};

如果你不能编辑html:

window.answer = function (elm) {
    var type = parseInt($(elm).index()) + 1;
    switch(type)
    {
        case 1:     
        {
            type += "st";
        }
        break;
        case 2:     
        {
            type += "nd";
        }
        break;
        case 3:     
        {
            type += "rd";
        }
        break;
        case 4:
        {
            type += "th";
        }
        break;
    }

    var message = 'elm is ' + type + ' of type';
    alert(message);
};
<ul id="myList">
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
</ul>
$("#myList").on("click", "li", function() {
    alert( $(this).index() );
});

因此,这就是事件委派(您可以在jquery文档中找到它(。它的有效作用是将一个事件侦听器附加到ul元素,过滤目标,使其仅在单击li类型的子项时引发事件,然后返回该子项在myList父项中的索引位置。