简体   繁体   中英

how to load js with jquery load method

I've tried to use the jQuery load method to load JavaScript:

<div id="update"></div>

<script type="text/javascript">
$('#update').load('find.html .themes', function(data) { 
    $(this).find('.themes').css({"width":"100%", "margin":"auto"});
});   
</script>

My file find.html:

    <div class="themes">
      <script> document.write('This is a test'); </script>
    </div>

Please can someone show me how to load JavaScript?

You should then use other ajax mehtod, eg:

$.get('find.html', function(data) {
  $('#update').empty().append($('<div/>', {
    html: data
  }).find('.themes').css({
    "width": "100%",
    "margin": "auto"
  }));
});

-jsFiddle-

empty().append() not html() which accepts only string (even you could pass object but it is not designed for it and can be it is buggy).

PS: Be aware in your case using document.write() would overwrite all document content, because this is how it works once document is fully parsed. So don't use it, even just for testing purpose.

If you don't have much things in your find.html div then you can access all the elements directly:

<script type="text/javascript">
  $('#update').load('find.html', function(data) {
    $(this).find('.themes').css({
      "width": "100%",
      "margin": "auto"
    });
  });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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