I'm trying to run this code, but it breaks my entire page. The page is marked up like this:

<script type="text/javascript">
$(document).ready(function() {
  $("#right_column h1").each( function() {  
   var link = $(this).html()+"<br />";
   document.write(link); 
});
});
</script>
<div id="right_column">
<h1>Company Profile</h1>
blablablablabla<br />

<h1>Nulla turpis nunc, dapibus ultricies.</h1>
blablablabla<br />
<h1>Pellentesque habitant morbi tristique proin laoreet.</h1>
blablablabla<br />

When i try to run the code, it only shows me the content of the 3 h1's, the rest of the page (the h1 themselves) aren't loaded anymore. When i remove the $(document).ready() function, and put the script block after everything, it works just fine.

有帮助吗?

解决方案

Don't use document.write after the document is read.

If you want to append to the page, do this :

  $(document).ready(function() {
     $("#right_column h1").each( function() {  
       var link = $(this).html()+"<br />";
       $(document.body).append($(link));   
     });
   });

其他提示

I will use something like this:

<script type="text/javascript">
$(document).ready(function() {
  $("#right_column h1").each( function() {  
   var link = $(this).html()+"<br />";
   $("#container-element").html('<a href="' + link + '">TEXT-YOU-WANT</a>');
});
});
</script>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top