简体   繁体   中英

Determining the calling div in a javascript function

I have a jquery function that returns the html for a randomized advertisement.

function getAd() {
    document.write( '<div>Some randomized ad html</div>' );
}

To insert the ad, I have this in my html file:

<div><script>getAd();</script></div>

This works, however, I'm trying to replace the document.write() code with something safer, like append(). So I'm trying this:

function getAd() {
    $(this).append( '<div>Some randomized ad html</div>' );
}

However, $(this) is the window and not the div.

I also tried this:

function getAd(elem) {
    $(elem).append( '<div>Some randomized ad html</div>' );
}

And in the html, I pass this:

<div><script>getAd(this);</script>

But once again, $(elem) is a window rather than the div. (In both of these cases, I get an "Cannot read property 'createDocumentFragment' of undefined" error.)

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.

Is there a way the calling function can determine the calling element so it can append the 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() :

function getAd(elem) {
    $(elem).append( '<div>Some randomized ad html</div>' );
}

$(document).ready(function(){
    $('[random-ad]').each(function(){
        getAd(this);
    });
});

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