2012-08-09 3 views
1

객체를 가져 오는 방법이 있습니까, 아니면 스크립트 내의 id가 jQuery 또는 다른 것을 사용하고 있습니까? 예를 들어자바 스크립트로 스크립트가있는 객체 가져 오기

이 예에서는

<div id="div1"> 
    <script type="text/javascript"> 
    var obj = ?? // this should be the "div1" div 
    </script> 
</div> 

, OBJ는 "div1"(또는 객체 자체)와 동일해야한다. 또 하나

이 예에서는

<p id="paragraph_7"> 
    <script type="text/javascript"> 
    var obj = ?? // this should be the "paragraph_7" p 
    </script> 
</p> 

는 OBJ "는 paragraph_7"(또는 객체 자체)와 동일해야한다.

스크립트 태그에 "id"를 입력하고 부모가 작동해야하지만 다른 방법이 있습니까? 항상 나는 <script> id를 알 수있는 것은 아닙니다.

미리 감사드립니다.

답변

2

스크립트가 순차적으로 실행되기 때문에 현재 실행중인 스크립트 태그는 그때까지 항상 페이지의 마지막 스크립트 태그입니다. 그래서, 스크립트 태그를 얻을, 당신은 할 수 있습니다 :

var scripts = document.getElementsByTagName('script'); 
var thisScriptTag = scripts[ scripts.length - 1 ]; 

그런 다음이를 사용할 수 있습니다

이의
var obj = thisScriptTag.parentNode; 


일부는 https://stackoverflow.com/a/3326554/1188942에서

+0

페이지가 구문 분석되는 동안 코드가 실행 된 경우에만 작동합니다. 함수에서 실행되면 함수가 호출 될 때 항상 페이지의 마지막 스크립트 요소를 제공합니다. – jordanbtucker

1

삽입 this code이며 작동합니다 . 기본적으로 스크립트를 쿼리 할 때 현재 실행중인 스크립트는 현재 DOM에있는 <scripts> 목록의 마지막 스크립트입니다.

<script> 
    //protect from the global scope using an immediate function 
    (function() { 

     //just being verbose 
     var scripts, scriptIndex, thisScript, parent; 

     scripts = document.getElementsByTagName('script'); 
     scriptIndex = scripts.length - 1; 
     thisScript = scripts[scriptIndex]; 
     parent = thisScript.parentNode.id; 

     //proof that we got the parent is to print the id 
     document.write(parent); 

    }());​ 

</script> 
관련 문제