使用jQuery/Javascript处理HTML元素组

Processing groups of HTML elements using jQuery/Javascript?

本文关键字:HTML 元素 处理 Javascript jQuery 使用      更新时间:2023-09-26

我有一个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
});