【问题标题】:Jquery get id or class from dynamic elementJquery从动态元素中获取id或类
【发布时间】:2012-05-21 13:21:15
【问题描述】:

假设我有 5 个来自 PHP 查询的元素(所以它是动态的) 如下图:

element 1 class=element id=id_1
element 2 class=element id=id_2
element 3 class=element id=id_3
element 4 class=element id=id_4
element 5 class=element id=id_5

我们通过知道它们的 class 或 id 来使用 jquery 事件,但在这种情况下,我们并不确切地知道它们的 id.

$("#id_3").click(function()
{ 
    //in this case we have known we want to add event when we click id_3
});

如何处理 PHP 查询中的动态元素?
例如,我们怎么知道我们点击了element 3和id_3?
$(????).click();必须填写什么?
当我使用类时,如何知道我从点击的类中引用了哪个 id?

【问题讨论】:

  • 您可以放置​​标签类型...例如,如果您的元素是 div,您可以执行 $("div").click() 然后在 click 事件中使用 this.id 来查看该元素的 id 是...

标签: javascript jquery dynamic element


【解决方案1】:

如果它们都具有相同的类,那么您可以使用类选择器。然后使用this 查找您想要的任何属性。

$('.element').click(
     $(this).prop('id');
); 

【讨论】:

    【解决方案2】:

    如果您只想添加点击,那么为什么不将其添加到服务器端生成的 html 中呢?

    【讨论】:

    • 这将违反尝试将表示层 (html/css) 与执行层 (js) 分开的概念。我不会推荐这个。
    【解决方案3】:

    您可以使用attribute starsWith 选择器和on 在动态创建的元素上绑定事件。

    $('body').on('click', '[id^=id]', function(e){
    
    });
    

    【讨论】:

      【解决方案4】:

      在您的示例中,所有元素都具有相同的类,因此您可以根据该类设置事件处理程序:

      $(".element").click(function() {
         // "this" refers to the clicked element
         // this.id will be the id of the clicked element
      });
      

      或者如果这些元素是动态的,在初始页面加载后的某个时间点通过 Ajax 加载,则使用委托事件处理程序:

      $("somecontainerelement").on("click", ".element", function() {
          // do something with this.id
      });
      

      “somecontainerelement”最好是添加动态元素的元素,但也可以是document。

      【讨论】:

      • 我喜欢这个解决方案。通过使用on,他减少了绑定在您的页面上的事件处理程序的数量。这提高了您的 javascript 的效率。如果您不熟悉on,请阅读。 api.jquery.com/on。 =)!
      【解决方案5】:

      这是我让它工作的唯一方法。比如你想获取属性ID或者被点击的元素的值……

      $("containerElem").on("click", "someElemID", function(evt) {
          var getElemID = $(evt.target).attr("id");
          var getVal = $(evt.target).val();
      });
      

      【讨论】:

        【解决方案6】:

        这在我们处理带有 id 或 class 的未知元素时非常有用

        $( document ).ready(function() {
          // user this if element is div 
          $('div[id^="id_"]').on('click', function() {  
            alert($(this).attr('id'));
          });
          // user this if element is input
          $('input[id^="id_"]').on('click', function() {  
            alert(this.id);
          });
        
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-07-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-12-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多