[英]Determining the calling div in a javascript function
I have a jquery function that returns the html for a randomized advertisement. 我有一个jquery函数,它返回用于随机广告的html。
function getAd() {
document.write( '<div>Some randomized ad html</div>' );
}
To insert the ad, I have this in my html file: 要插入广告,请在html文件中添加以下广告:
<div><script>getAd();</script></div>
This works, however, I'm trying to replace the document.write() code with something safer, like append(). 这可行,但是,我试图用更安全的东西(例如append())替换document.write()代码。 So I'm trying this:
所以我正在尝试:
function getAd() {
$(this).append( '<div>Some randomized ad html</div>' );
}
However, $(this) is the window and not the div. 但是,$(this)是窗口而不是div。
I also tried this: 我也试过这个:
function getAd(elem) {
$(elem).append( '<div>Some randomized ad html</div>' );
}
And in the html, I pass this: 在html中,我通过了:
<div><script>getAd(this);</script>
But once again, $(elem) is a window rather than the div. 但是再一次,$(elem)是一个窗口而不是div。 (In both of these cases, I get an "Cannot read property 'createDocumentFragment' of undefined" error.)
(在这两种情况下,我都会收到“无法读取未定义的属性'createDocumentFragment'”的错误。)
I realize I can assign an id to the div and then pass the id to the getAd() function, but I have hundreds of these calls on the website (and sometimes several on the same page) and I would prefer not to have to assign and then pass an id every time I call this function. 我知道我可以为div分配一个ID,然后将该ID传递给getAd()函数,但是我在网站上有数百个此类调用(有时在同一页面上有多个调用),所以我宁愿不必分配然后每次调用此函数时传递一个id。
Is there a way the calling function can determine the calling element so it can append the html? 调用函数是否可以确定调用元素,以便可以附加html?
Thanks! 谢谢!
You can add a common attribute ( or a class ) to all your elements: 您可以向所有元素添加通用属性( 或类 ):
<div random-ad>
And then, call your function using $.each()
: 然后,使用
$.each()
调用函数:
function getAd(elem) {
$(elem).append( '<div>Some randomized ad html</div>' );
}
$(document).ready(function(){
$('[random-ad]').each(function(){
getAd(this);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.