对js文件中的html内容执行javascript

对js文件中的html内容执行javascript,javascript,jquery,html,Javascript,Jquery,Html,这真让人头疼 我有一个简单的js文件,它只包含html内容的document.write()块,我需要对其执行jquery 为了更好地理解问题,js文件如下所示: <script language="JavaScript" src="http://external-java-file.js"/> <script> $(document).onload(function(){ $("div.newsContainer").css("display","none"); })

这真让人头疼

我有一个简单的js文件,它只包含html内容的document.write()块,我需要对其执行jquery

为了更好地理解问题,js文件如下所示:

<script language="JavaScript" src="http://external-java-file.js"/>
<script>
$(document).onload(function(){
$("div.newsContainer").css("display","none");
});
</script>

在一批部门中发布新闻。问题是,我需要在每个单独的文章div上执行javascript(将其包含在自定义javascript“滚动器”中)。我是否需要先“隐藏”整个新闻块,然后每个div将其添加到我的滚动器中。 基本上我从js文件中得到了这个:

<div class="newsContainer">
<div class="newsArticle">bla bla bla</div>
<div class="newsArticle">bla bla bla</div>
<div class="newsArticle">bla bla bla</div>
</div>

呜呜呜呜
呜呜呜呜
呜呜呜呜
由于所有这些都是通过document.write从这个臭烘烘的外部js文件中获得的,因此我无法使用这样一个单独的代码块来访问它:

<script language="JavaScript" src="http://external-java-file.js"/>
<script>
$(document).onload(function(){
$("div.newsContainer").css("display","none");
});
</script>

$(文档).onload(函数(){
$(“div.newscanner”).css(“显示”、“无”);
});
我很确定我已经走到了尽头,但我想看看是否有聪明的头脑有你想要使用的天才解决方案

$(document).ready(function() {
// .. put code here.
});
这将确保页面和其他JS已首先加载

Firefox中的Firebug控制台是您的朋友,因为您可以在页面上测试您的jQuery。

尝试以下方法:

HTML
如果脚本使用document.write(),则在页面加载并以这种方式编辑后,您将能够访问其容器#news。

制作css样式以最初隐藏新闻容器:

.newsContainer {
  display: none;
}
然后在jQuery的document ready函数中添加其他内容:

$(function() {
  // do your stuff here
});

如果你不知道外部脚本什么时候能完成新闻div的任务,请使用JavaScript的
setTimeout
。还记得在完成后将.newsContainer设置为可见。

你不能编辑外部js文件吗?@MeLight,遗憾的是没有-。-我希望我能。如果我们使用
$(document)。ready()
而不是onload您还可以使用
$(function(){/..code});
这是jQuery的速记等价物。我更喜欢使用上面的方法,让下一个支持它的人更清楚地知道,它只会在DOM加载后执行。我想归结为首选项:)这很公平,我想我会把它包括在懒惰的人(像我一样):)