简体   繁体   中英

Hiding element after firing click handler

Say I have the following code to add a clickable image after a set of elements. The click handler fires every time the image is clicked which is not what I want. I guess hiding the image using .hide() in the click handler is one approach but I can't figure out how to refer to the img element in the click handler.

Help? Thanks

  $(...)
  .after($('<img src="..."/>')
  .css("cursor","pointer")
  .attr("title","Click here for ...")
  .click(function(){ ... }

It would probably be simplest and most readable to break it into two lines:

var e = $('<img src="..."/>');
  $(...)
  .after(e)
  .css("cursor","pointer")
  .attr("title","Click here for ...")
  .click(function(){ ... use e here...  }

Although you could use next as I did in this example aka:

$('p')
  .after($('<img src="..."/>'))
  .css("cursor","pointer")
  .attr("title","Click here for ...")
  .click(function() { 
      $(this).next().css("border", "solid white 5px");

  })

So that uses the niceness of this to fetch the element you are looking for without any temporaries. http://jsbin.com/ulewo

$("#foo").click(function () {
    $(this).hide(); /* This refers to the item(s) being clicked */
})

You could give your image an unique id in order to fetch it:

$(...)
  .after($('<img id="myimage" src="..."/>')
  .css("cursor","pointer")
  .attr("title","Click here for ...")
  .click(function()
  { 
      var img = $('#myimage');
  }

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