代码之家  ›  专栏  ›  技术社区  ›  Jake N

将数据传递给jquery click()函数

  •  14
  • Jake N  · 技术社区  · 14 年前

    我有一个这样简单的跨度

    <span class="action removeAction">Remove</span>
    

    此范围在表中,每行都有一个删除范围。

    然后,当单击该范围时,我使用Ajax调用一个URL。Ajax事件需要知道该行的对象ID吗?将该ID输入Click函数的最佳方法是什么?

    我想我可以做这样的事

    <span class="action removeAction" id="1">Remove</span>
    

    但是ID不应该以数字开头?正确的?然后我想我能做到

    <span class="action removeAction" id="my1">Remove</span>
    

    然后从身份证上去掉“我的”部分,但这看起来很糟糕!

    下面是我的点击事件和我的Ajax事件。

    <script type="text/javascript" language="text/javascript">
    
    $(document).ready(function()
    {
    
        $(".removeAction").click(function()
        {
            //AJAX here that needs to know the ID            
        }
    });
    
    </script>
    

    我确信有一个很好的方法可以做到这一点?

    注:我不想找

    $(this).attr("id");
    

    我想传递不止一条信息

    谢谢。满意的。

    5 回复  |  直到 11 年前
        1
  •  14
  •   Mathias Bynens    11 年前

    如果您坚持使用旧式HTML 4.01或XHTML:

    $('.removeAction').click(function() {
     // Don’t do anything crazy like `$(this).attr('id')`.
     // You can get the `id` attribute value by simply accessing the property:
     this.id;
     // If you’re prefixing it with 'my' to validate as HTML 4.01, you can get just the ID like this:
     this.id.replace('my', '');
    });
    

    顺便说一下,在HTML5中, the id attribute can start with a number or even be a number .

    同样,如果您仍然在使用HTML5,那么您最好使用自定义数据属性,如:

    <span class="action removeAction" data-id="1">Remove</span>
    
        2
  •  3
  •   Flatlin3    14 年前

    $(this)在click函数中表示单击的元素

    $(".removeAction").click(function() {
        //AJAX here that needs to know the ID
        alert($(this).attr('id'));           
    }
    
        3
  •  1
  •   GlenCrawford    14 年前

    以下代码将为您获取单击的 span . 使用ID并不完美,但它会起作用。

    $(".removeAction").click(function() {
      alert($(this).attr("id"));
    });
    
        4
  •  1
  •   Sunny    14 年前

    您可以在每一行上都有一个隐藏字段,用于存储JSON对象中所需的ID和/或其他数据,并使用该字段而不是使用SPAN标记进行黑客攻击。

    <tr>
    <td>
    <span class="action removeAction">Remove</span>
    <input type="hidden" value="1" />
    </td>
    </tr>
    
    $('.removeAction').click(function(){
      var id = $(this).next().val();
      // do something...
    });
    

    高温高压

        5
  •  0
  •   dakull    14 年前

    您可以尝试jquery.data(): http://api.jquery.com/jQuery.data 但这意味着服务器端生成的JS代码将在页面加载时执行,这样您就可以存储ID以备日后重用(您的删除操作)。

    // this part would have to be server 'generated'
    // and by that I'm referring  to the '<?=$row_id?>'
    $('table .remove').each(function(){
    
       var MyElem = $(this);
       MyElem.data('id', <?=$row_id?> );
    
       MyElem.click(function(){
          the_id = $(this).data('id');
          // ajax call goes here
       });
    
    });