2012-01-10 2 views
0

이 질문은 좀 바보 같아 보이지만 ... 다른 자바 스크립트 코드에 인라인 자바 스크립트 코드를 삽입하는 것이 가능한지 궁금합니다. 이 명확 넣어하자 :인라인 자바 스크립트 코드를 다른 자바 스크립트/jquery 코드에 삽입 할 수 있습니까?

jQuery('.gplus').append('<g:plusone annotation="inline"></g:plusone>'); 

이 버튼이 제대로 작동하기 위해 외부 JS를 필요로 다음과 같이 내가 jQuery를 통해 추가하는 구글 플러스 버튼을 넣어려고

.

var gplusjs = ' 
<script type="text/javascript"> 
    (function() {var po = document.createElement("script"); 
    po.type = "text/javascript"; po.async = true; 
    po.src = "https://apis.google.com/js/plusone.js"; 
    var s = document.getElementsByTagName("script")[0]; 
    s.parentNode.insertBefore(po, s); 
    })(); 
</script>'; 
jQuery('#js').append(gplusjs); 

이의 결과는 HTML로 인쇄 된 코드이지만, 스크립트로 해석되지 : 난 할 노력하고있어이 일을 외부 JS를 삽입합니다. 이것은 가능합니까? 나는 바보 야? 감사! 더 쉽게,

var po = document.createElement("script"); 
po.type = "text/javascript"; po.async = true; 
po.src = "https://apis.google.com/js/plusone.js"; 
var s = document.getElementsByTagName("script")[0]; 
s.parentNode.insertBefore(po, s); 

을 또는 :

답변

3

그냥 일반적으로 그 코드를 실행해야

jQuery를가 추가 스크립트가 작동하지 않기 때문이다
$.getScript("https://apis.google.com/js/plusone.js"); 
2

. 구식 방식으로 수행하십시오.

var gplusjs = '(function() {var po = document.createElement("script");po.type = "text/javascript"; po.async = true;po.src = "https://apis.google.com/js/plusone.js";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(po, s);})();'; 
var script = document.createElement("script"); 
script.textContent = gplusjs; 
document.head.appendChild(script); 

다중 줄 문자열 리터럴은 JS에 없습니다.

+2

사실, 줄 바꿈 문자열 리터럴이 아닌'\\ – SLaks

+0

@SLaks '를 사용하여 각 줄 바꿈 문자를 이스케이프 처리하여 여러 줄의 문자열 리터럴을 만들 수 있습니다. 새 줄 문자를 이스케이프 처리하는 것은 더러운 해킹입니다. – Raynos

+0

@SLaks 추가로 제쳐두고 그것은 무효 ES3이야, 당신은 ES5가 그것을 허용하는지 여부를 알 수 있습니까? – Raynos

관련 문제