有没有更好(更明智)的方法来实现同样的目标
Is there a better (more sensible) way to achieve this same goal?
我对以前的问题有一个有效的解决方案,但它不像是好的程序员习惯。有更好的解决方案吗?还是这只是一条路?
这是我的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父项中的索引位置。
相关文章:
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- 如何用Typescript用自定义方法实现类数组
- 将setTimeout()包装器实现为Element.prototype中的方法
- 在 Javascript 中实现解耦代码/回调的正确方法是什么?
- 6502仿真ADC和SBC的正确实现方法
- AngularJS:有没有比指定的方法更好的方法来实现这一点
- 有哪些方法可以在html和javascript中实现持久,可共享的存储
- 在对象类上实现 jquery 作用域的最佳方法
- 在java实现中寻找javascript md5方法
- 在Javascript中实现GroupBy最有效的方法是什么
- 在node_redis上实现findBy方法,但它没有'不起作用
- 使用clearInterval方法实现的是将区间变量引用设置为null,而不是
- ES6类:在另一个函数中包装方法实现
- 方法实现差异.需要一些了解
- CanJs 模型服务方法实现
- 是否可以使用这种方法实现数组乘法
- 使用私有实例方法实现 TS/JS 装饰器
- AngularJS DOM修改删除事件->需要可行的变通方法实现模式
- 用子方法实现函数可以吗
- 在哪里可以找到“;javascript”;V8 DOM方法实现的源代码(document.createElement()