【问题标题】:alert individual attribute value [duplicate]警报单个属性值[重复]
【发布时间】:2023-03-18 23:51:01
【问题描述】:

我想通过它的名称属性来识别每个元素。每个元素都有相同的类,最终会包含不同的动态信息。

例如,我希望以下代码提醒单个元素的名称值:

html:

<p class="pexample" name="0">this is p #1</p>
<p class="pexample" name="1">this is p #2</p>
<p class="pexample" name="2">this is p #3</p>

jquery:

$('p').on('click', function() {
    if ($('p').attr('name') !== undefined) {
        alert($('p').attr('name'));
    }
})

这是一个 jsfiddle..http://jsfiddle.net/XG7nd/1/

但是,此代码仅提醒初始元素名称值。非常感谢您的帮助。

【问题讨论】:

  • 我想你想要if ($(this).attr('name') 而不是$('p')。后者选择页面上的所有p元素...

标签: javascript jquery if-statement


【解决方案1】:

应该这样做:

$('p').on('click', function() {
   var name = $(this).attr('name');// `this` here refers to the current p you clicked on
   if (name ) {
        alert(name); 
    }
})

在执行$('p').attr('name') 时,这将始终为您提供集合中第一个项目的名称。

Demo

【讨论】:

    【解决方案2】:

    试试这个:

    $(document).on('click','p', function() {
        alert($(this).attr('name'));
    });
    

    DEMO

    【讨论】:

    • If 语句不准确。它还应该使用this
    【解决方案3】:

    你想使用$(this)

    $('p').on('click', function() {
        if($(this).attr('name') !== 'undefined') {
            alert($(this).attr('name'));
        }
    });
    

    【讨论】:

      【解决方案4】:

      发生这种情况是因为您在每次点击时都获得了第一个 &lt;p&gt;name 属性。您需要指定事件的来源:

      $('p').on('click', function() {
      if ($(this).attr('name') !== undefined) {
          alert($(this).attr('name'));
      }
      })
      

      注意,jQuery 选择器返回一个匹配元素的数组。您必须使用 this 关键字来获取当前上下文中元素的句柄。

      FIDDLE

      【讨论】:

        【解决方案5】:

        说明

        即使在 click 上,您也会继续寻找 p 元素,因此它会选择找到的第一个元素。

        您的代码内容:

        p被点击时:

        • 查找p 元素并提醒其属性。

        你真正想要的:

        p被点击时:

        • 提醒被点击元素的属性

        解决方案

        选择this的属性,即被点击的元素。

        JSFiddle

        JavaScript

        $('p').on('click', function() {
            if ($(this).attr('name') !== undefined) {
                alert($(this).attr('name'));
            }
        })
        

        阅读更多关于this keyword的信息。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多