JQuery Value vs Reference
I am trying to progressivel开发者_JAVA技巧y enhance a div element containing an a tag, so that the content of the div is updated and the click event of the div opens the href of the (before Javascript modification), a.
I have the following code:
$("div")
.click(function(){
window.open($("div a").attr("href"));
})
.html(">");
<div>Some text and <a href="link.html">a link</a></div>
The problem is, when the click event happens, the content of the <div>
has already been updated and so the href attribute is no longer valid.
Any assistance on how I would write this so the url is remembered would be greatly appreciated.
Something along these lines should do the trick:
$("div").each(function () {
var url = $('a', this).attr('href');
$(this).click(function () { window.open(url); }).html(">");
});
If there is only one div
, you can skip the .each
and simply save the href
value into a variable before replacing the content. Or use a closure:
$("div")
.click((function (url) {
return function () { window.open(url); };
})($("div a").attr('href')))
.html(">");
精彩评论