[英]Is there a way to get the DOM element that contained the inline JS script that called a function?
例如
<script>
function foo(){...}
</script>
<div><script>foo();</script></div>
<span><script>foo();</script></span>
我想讓foo從div調用時返回“ abc”,從跨度調用時返回“ 123”。
這可能嗎?
您可以只獲取DOM中當前的最后一個元素。
內聯<script>
塊中的代碼在瀏覽器解析頁面時執行。 因此,最后一個DOM元素將在腳本之前。
閱讀您的評論后,我認為您應該做其他事情:
#ad1_empty
, #ad2_empty
,...) #ad1_full
, #ad2_full
,...) //代碼
<div id="ad_empty"><!-- placeholder --></div>
<div id="ad_content" style="display: none;">
<script src="[ad resource]"></script>
<script>inline ad script</script>
</div>
<script>
function replace( oldel, newel, show ) {
if ( typeof newel == "string" )
newel = document.getElementById( newel );
if ( typeof oldel == "string" )
oldel = document.getElementById( oldel );
if ( newel && oldel )
oldel.parentNode.replaceChild( newel, oldel );
if ( show )
newel.style.display = "";
}
window.onload = function() {
replace( "ad_empty", "ad_content", true );
replace( "ad_empty2", "ad_content2", true );
};
</script>
可以做您本來想做的事,順便說一句(但這沒用)
function foo() {
var scripts = document.getElementsByTagName("script");
var parent = scripts[scripts.length-1].parentNode;
var tag = parent.nodeName.toUpperCase();
if (tag == "DIV") {
alert("called from a <div>");
} else if (tag == "SPAN") {
alert("called from a <span>");
}
}
不,這是不可能的。 您將必須手動傳遞某種參數以標識從何處調用它。
沒有辦法做到這一點,可以用許多不同的方式來調用腳本,只是沒有足夠的需要以任何方式將其放入規范中。
我可以想象有整體做你要完成的一個更簡單的方法,嵌入<script>
單個元素內,立足什么關<script>
元素的位置不”似乎是一個合理方法。
那么...您要在這里最終完成什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.