简体   繁体   中英

function called in wrong button click event using jquery

I am having 2 div elements say div1, div2and 2 buttons 'add image' and 'discard image'(initially hidden).

When I click add image button, it adds 2 images to all div. when image inside any div get clicked 'discard image' button get visible,so when i clicked this discard some functionality.

I have written click event on image in both div separately as well discard btn click function as below.

   if($.trim($("#div1").html())=='')
   {
      $("#div1").append("<img id='grpA0' width='60px' height='60px' src="1.png">");
      $("#div1").append("<img id='grpA0' width='60px' height='60px' src="2.png">");

      $("#grpA0").click(function() 
      {
        $("#discard_image").show();////shows hidden discard btn
      });
      $("#discard_image").click(function()
     {
        alert("in div1 discard");
        /// some code                                   
    });
}

if($.trim($("#div2").html())=='')
{
    $("#div2").append("<img id='grpB0' width='60px' height='60px' src="3.png">");
    $("#div2").append("<img id='grpB0' width='60px' height='60px' src="4.png">");

    $("#grpB0").click(function() 
    {
        $("#discard_image").show(); ////shows hidden discard btn
    });
    $("#discard_image").click(function()
     {
         alert("in div2 discard");
        /// some code                                   
    });
} 

my question is when i clicked image from div1 ,discard btn shown but on discard button click both alerts are shown. i tried to send e as event in discard click and used e.preventDefault(); but its not working

id attribute of html should be unique in your html pages.

You created 2 div with same id. 1st in div1 2nd in div2.

So Basically you are binding two elentet your discard element. This is why you are getting both alert.

$("#discard_card").click(function()
  {
    alert("in div1 discard");
    /// some code                                   
});
$("#discard_card").click(function()
  {
     alert("in div2 discard");
    /// some code                                   
});

To solve this problem you need to give unique id for both div. You can try discard_1, discard_card_1 and discard_2, discard_card_2

if($.trim($("#div1").html())=='')
   {
      $("#div1").append("<img id='grpA0' width='60px' height='60px' src="1.png">");
      $("#div1").append("<img id='grpA0' width='60px' height='60px' src="2.png">");

      $("#grpA0").click(function() 
      {
        $("#discard_1").show();
      });
      $("#discard_card_1").click(function()
     {
        alert("in div1 discard");
        /// some code                                   
    });
}

if($.trim($("#div2").html())=='')
{
    $("#div2").append("<img id='grpB0' width='60px' height='60px' src="3.png">");
    $("#div2").append("<img id='grpB0' width='60px' height='60px' src="4.png">");

    $("#grpB0").click(function() 
    {
        $("#discard_2").show();
    });
    $("#discard_card_2").click(function()
     {
         alert("in div2 discard");
        /// some code                                   
    });
}

Please also update the id value in html as well.

Since you are using the same discard button for both items, it's a good idea to unbind listeners before binding new ones.

$("#discard_card").unbind();

Furthermore, do this when required (ie on show):

$("#grpB0").click(function() {
  $("#discard").show();

  $("#discard_card")
  .unbind()
  .on('click', function() {
    alert("in div2 discard");
    /// some code                                   
  });
});

Full corrected code (including " changed to ' inside quotes):

if ($.trim($("#div1").html()) == '') {
  $("#div1").append("<img id='grpA0' width='60px' height='60px' src='1.png'>");
  $("#div1").append("<img id='grpA0' width='60px' height='60px' src='2.png'>");

  $("#grpA0").click(function() {
    $("#discard_image").show(); ////shows hidden discard btn
    $("#discard_card").unbind()
      .on('click', function() {
        alert("in div1 discard");
        /// some code                                   
      });
  });

}

if ($.trim($("#div2").html()) == '') {
  $("#div2").append("<img id='grpB0' width='60px' height='60px' src='3.png'>");
  $("#div2").append("<img id='grpB0' width='60px' height='60px' src='4.png'>");

  $("#grpB0").click(function() {
    $("#discard_image").show(); ////shows hidden discard btn
    $("#discard_card").unbind()
      .on('click', function() {
        alert("in div2 discard");
        /// some code                                   
      });
  });

}

Here is a working jsfiddle example: https://jsfiddle.net/maxbilbow/cyazd4mn/2/

You have a couple of issues, one big one being that id attribute should be unique. Use class to designate multiple tags.

When you need to attach events specific to certain elements in your DOM, using a data-[something] attribute is often a good idea that allows you to use just a single event handler instead of attaching separate handlers for each item.

I'm guessing at your html structure, but this snippet is an example of what I mean by using data attributes:

 if($.trim($("#div1").html())=='') { $("#div1").append("<img class='group' id='one' width='60px' height='60px' src='1.png'>"); $("#div1").append("<img class='group' id='two' width='60px' height='60px' src='2.png'>"); } if($.trim($("#div2").html())=='') { $("#div2").append("<img class='group' id='three' width='60px' height='60px' src='3.png'>"); $("#div2").append("<img class='group' id='four' width='60px' height='60px' src='4.png'>"); } $('.group').click(function(event) { var divNum = $(event.target).closest('div').data('num'); $(".discard[data-num='" + divNum + "']").show(); }); $('.discard_card').click(function(event) { var divNum = $(event.target).closest('div').data('num'); alert('Clicked discard for div' + divNum); }); 
 #one { background-color: yellow; } #two { background-color: pink; } #three { background-color: grey; } #four { background-color: cyan; } .discard { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="div1" data-num="1"></div> <div class="discard" data-num="1"> <button class="discard_card">Discard</button> </div> <div id="div2" data-num="2"></div> <div class="discard" data-num="2"> <button class="discard_card">Discard</button> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM