使用jQuery/Javascript处理HTML元素组
Processing groups of HTML elements using jQuery/Javascript?
我有一个HTML 5页面,里面有几篇文章。每篇文章都有一个标题为"MyAttribute"的自定义属性:
<html>
<article MyAttribute="x">
<article MyAttribute="y">
<article MyAttribute="z">
</html>
我想创建一个函数,做一些类似下面的伪代码:
for each article {
get MyAttribute from the article
if MyAttribute == x {do this}
if MyAttribute == y {do that}
if MyAttribute == z {do something else}
}
使用jQuery/JavaScript最有效的方法是什么?
不使用自定义属性,我建议将"MyAttribute"放在data-*属性中,如下所示:
<html>
<body>
<article data-myattribute="x"></article>
<article data-myattribute="y"></article>
<article data-myattribute="z"></article>
</body>
</html>
这会创建"更有效"的HTML。然后你可以这样写javascript:
$('article').each(function (){
switch ($(this).data('myattribute')){
case 'x':
//do something for x
alert('this is case X');
break;
case 'y':
//do something for y
alert('this is case Y');
break;
case 'z':
//do something for z
alert('this is case Z');
break;
}
});
我还为您创建了结果的jsFiddle
$('article').each(function() {
if (this.MyAttribute == 'x')
//...
else if (this.MyAttribute == 'y')
//...
else if (this.MyAttribute == 'z')
//...
//etc.
});
如果您在服务器端插入这些属性,则页面将无法验证并且可能会触发浏览器的怪癖模式。
你可以先使用data-myattribute,然后再使用data()。
$('article').each(function() {
var MyAttribute = $(this).attr('data-myattribute');
if (MyAttribute == 'x')
//code
else if (MyAttribute == 'y')
//code
else if (MyAttribute == 'z')
//code
});
相关文章:
- 如何设置html元素填充的动画
- 删除对HTML元素的拖动
- 如何使用jquery迭代具有相同属性的html元素并查找onclick事件
- 如何使用JQuery在Javascript中转换字符串中的HTML元素
- 一个html元素的克隆次数太多
- 使用AngularJS Directive WHITOUT$scope创建一个动态html元素
- 为什么我在Internet Explorer上看不到html元素
- 重新排列HTML元素的顺序并更改内容
- 使用.on动态添加jquery/js不知道的html元素
- 如果类不是一个选项,如何在使用 jQuery 时控制(避免)嵌套 html 元素的样式
- 如何将html元素添加到tampermonkey中
- 访问html元素值javascript
- 如何在HTML元素上创建函数,而不是将元素作为参数传递
- 自定义HTML元素属性未显示-Web组件
- 让HTML元素充当停止滚动的锚点
- 将html元素插入到文本字符串中,以匹配另一个html字符串
- 替换HTML元素中的字符
- 如何将html元素添加为生成的内容
- 如何使用JavaScript在没有html dom的情况下隐藏html元素
- 使用JS加载HTML元素