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 i开发者_如何学Pythonmage 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(){ ... }
$("#foo").click(function () {
$(this).hide(); /* This refers to the item(s) being clicked */
})
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
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');
}
精彩评论