简体   繁体   English

从外部html文件运行javascript

[英]run javascript from an external html file

I have 2 html pages, one that uses: 我有2个html页面,其中一个使用:

        $.get('alertjquery.html', null, function(tsv) {
            alert(tsv);
        });

To get the data from the other webpage. 从另一个网页获取数据。 The other webpage contains: 另一个网页包含:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>    
<script>

    $(document).ready(function() {
    var data = $('#test').text($('section').length);
});

</script>
</head>
    <body>
     <section>
     This should be counted
     </section>
 <section>
 This should be counted
 </section>
 <section>
 This should be counted
 </section>
 <section>
 This should be counted
 </section>
 <section>
 This should be counted
 </section>

  There are currently <b id='test'></b> alerts


</body>

I want to get the data that the javascript creates. 我想获取JavaScript创建的数据。 Is this possible to do? 这可能吗? If so how would I go about it. 如果是这样,我将如何处理。 The get works but but gets the static webpage so doesn't run the javascript 该get可以运行,但是会获取静态网页,因此不会运行javascript

No, it's not possible. 不,不可能。

However, you can parse this data and count the paragraphs in other way. 但是,您可以解析此数据并以其他方式对段落进行计数。

What you could do is this. 您能做的就是这个。 First load in the second HTML with AJAX, the create a DOM object. 首先使用AJAX加载第二个HTML,创建一个DOM对象。 then extract the innerHTML of your script tag. 然后提取脚本标记的innerHTML。 You can change document to nameofdomobject in this string. 您可以在此字符串中将文档更改为nameofdomobject。 and then evaluate it. 然后对其进行评估。

SOrry that i don't provide code, but this should help you 抱歉,我没有提供代码,但这对您有帮助

You should apply the script inside $.get as such: 您应该这样在$.get应用脚本:

$.get('alertjquery.html', function(){
    var data = $('#test').text($('section').length);
    console.log(data)
});

However, it is better if you use $.load ; 但是,最好使用$.load ;

$('.container').load('alertjquery.html', function(){
    var data = $('#test').text($('section').length);
    console.log(data)
})

You can simplify this process by creating a function. 您可以通过创建函数来简化此过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM