开发者

dynamically insert javascript into <head> tag

开发者 https://www.devze.com 2022-12-29 06:39 出处:网络
I am using CEWP (webpart) and putting this code in there. But this code is not going inside <head> tag. I need to insert this code in <head> tag,

I am using CEWP (webpart) and putting this code in there. But this code is not going inside <head> tag. I need to insert this code in <head> tag,

<script src="http://code.jquery.com/jquery-latest.js"><开发者_运维技巧/script>

<script type="text/javascript">
$("*").each(function () { if ($(this).children().length == 0) { $(this).text($(this).text().replace('Respuesta','Responder')); } });
</script>

How can I do this? How this code will work in CEWP webpart?


Firstly, you can put the code in the <head> if you set it to run at document ready time.

However, it's still not going to work. You're iterating over all tags. Including <html>, which will be the first one selected by $('*').

So you read all the text inside the <html> element (ie. the entire document text), do a string replace on it, then write it back to the html text(). Replacing all the previous text and element content of the <html> element with a single simple text string. And thereby destroying every other element on the page. Oops.

What you want to do is find every text node and do a separate string replace on it:

$(document).ready(function() {
    $('*').each(function() {
        for (var i= this.childNodes.length; i-->0;) {
            var child= this.childNodes[i];
            if (child.nodeType===3) // TEXT_NODE
                child.data= child.data.replace(/Respuesta/g, 'Responder');
        }
    });
});

(Note there are still a bunch of possible edge cases here with form fields and other elements where changing the text inside them might not do what you expect.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号