move onclick function to other element with jquery - reading attr() returns function
I have an <img src="blabla.png" onclick="someFunction();">
tag that I want to replace with an <a>
tag (created dynamically).
I want to move the onclick from the to the but when I read attr("onclick")
it returns:
function onclick(event) {
someFunction();
}
How can I extract only the someFunction();
call and set this to the onclick of the <a>
tag?
After the answer I used it like this:
$(function(){
$(".content img[src*=images]").each(function(){
$(this).after("<a href=# class='button'></a>");
$(this).next().text($(this).attr("alt"));
$(this).next().click(this.onclick);
/* remove old img */
$(this).remove();
}开发者_Python百科);
});
Use the this.onclick
instead of $(this).attr('onclick'). It will be a function type and you can simply set the a.onclick = img.onclick
.
Ideally however the image would have a click handler and would be bound unobtrusively.
var someFunction = function(){};
$('img').click(someFunction);
Then you could use the same function on the a
$('a').click(someFuncion);
精彩评论