weixin_33694172 2016-12-06 23:40 采纳率: 0%
浏览 18

呼叫某个类别/ ID

I have a shopping cart, and it once an item is added a trash icon appears. There is a current script that works but it targets all of the 'onclick' functions in the page. I would just like it to target this one (garbage can one). Here is the code for the icon.

<td class="total">
  <span class="close" style="color:#f00;">
    <i class="fa fa-trash"></i>
  </span>
</td>

Now the current JavaScript is like this:

$( document ).ready(function() {

$('body').on('click','.close', function(){
var here = $(this);
var rowid = here.closest('tr').data('rowid');

Theres more JavaScript although I'm just showing the beginning.

I tried something like this, but nothing worked.

$( document ).ready(function() {
  var trash = document.getElementsByClassName("fa fa-trash");
  trash.on('click', '.close', function(){
  var here = $(this);

I don't know if I am on the right track.

  • 写回答

2条回答 默认 最新

  • weixin_33716154 2016-12-06 23:45
    关注

    Replace

    var trash = document.getElementsByClassName("fa fa-trash");
    

    with

    var trash = $(".fa.fa-trash");
    

    If you want to use JS to fetch the elements, using document.getElementsByClassName then you will have to iterate over a for loop and bind the events specifically for each.

      var trashes = document.getElementsByClassName("fa fa-trash");
      for(var i=0; i< trashes.length; i++) {
         var $trash = trashes[i];
    
         $trash.on('click', '.close', function() {
    
        ...
      } // end of for loop
    

    Use querySelectorAll

     var trash = document.querySelectorAll(".fa.fa-trash");
      trash.on('click', ...
    
    评论

报告相同问题?