Passing data to a jQuery click() function

后端 未结 5 2033
独厮守ぢ
独厮守ぢ 2021-01-01 21:21

I have a simple span like so

Remove

This span is within a table, each row has a remo

相关标签:
5条回答
  • 2021-01-01 22:05

    If you insist on using old-school HTML 4.01 or 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', '');
    });
    

    By the way, in HTML5, the id attribute can start with a number or even be a number.

    Then again, if you’re using HTML5 anyway, you’re probably better off using custom data attributes, like so:

    <span class="action removeAction" data-id="1">Remove</span>
    
    0 讨论(0)
  • 2021-01-01 22:07

    You could have a hidden field on each row which stores the ID and/or other data needed in a JSON object & use that instead of hacking around with the span tag.

    <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...
    });
    

    HTH

    0 讨论(0)
  • 2021-01-01 22:11

    The following code will get you the ID of the clicked span. Using the ID isn't perfect, but it will work.

    $(".removeAction").click(function() {
      alert($(this).attr("id"));
    });
    
    0 讨论(0)
  • 2021-01-01 22:21

    You could try jQuery.data(): http://api.jquery.com/jQuery.data , but that would mean server-side generated js code to execute when the page loads so that you can store the ids for later reuse (your remove action)

    // 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
       });
    
    });
    
    0 讨论(0)
  • 2021-01-01 22:22

    $(this) within your click function represents the clicked element

    $(".removeAction").click(function() {
        //AJAX here that needs to know the ID
        alert($(this).attr('id'));           
    }
    
    0 讨论(0)
提交回复
热议问题