我正在尝试用其他内容替换div的内容,这两个内容都是JavaScript代码,但是,当我按下调用该函数的按钮时,整个页面都会刷新,并且该函数中的新JavaScript会加载到页面上(而且看起来也损坏了)

这是我使用的JavaScript函数

function refresh(){
alert("button pressed");
$("#tweet1").html('<script>new TWTR.Widget({version: 2,  type: "search",  search: "#abbaseya",  interval: 15000,  subject: "widget",  width: 300,  height: 360,theme: {    shell: {      background: "#8ec1da",      color: "#ffffff"    },tweets:{background:"#ffffff",color:"#444444",links:"#1985b5"}},features:{scrollbar:true,loop:true,live:true,behavior:"default"}}).render().start();<\/script>');
}


我究竟做错了什么? tweet1只是一个带有id的div,上面的函数被一个按钮调用

这是我正在使用的按钮,我在html中有一个表单

<form style="float:right; ">
        <input type="text"/><input type="button" value="Refresh" onclick="refresh()"/>
        </form>

最佳答案

确实没有理由将内联脚本标签动态注入到DOM元素中。只需像常规JavaScript一样执行script标签的主体即可。

function refresh() {
  alert("button pressed");
  new TWTR.Widget({version: 2,  type: "search",  search: "#abbaseya",  interval: 15000,
  subject: "widget",  width: 300,  height: 360,theme: {    shell: {      background:
   "#8ec1da",      color: "#ffffff"    },tweets:
  {background:"#ffffff",color:"#444444",links:"#1985b5"}},features:
  {scrollbar:true,loop:true,live:true,behavior:"default"}}).render().start();
  return false; // prevent refresh
}

07-24 09:50
查看更多