把JavaScript放入jquery .html函数中 [英] put javascript into jquery .html function

查看:65
本文介绍了把JavaScript放入jquery .html函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我使用的JavaScript函数

  function refresh(){
alert(button pressed);
$(#tweet1)。html('< script> new TWTR.Widget({version:2,type:search,search:#abbaseya,interval:15000,subject: ,width:300,height:360,theme:{shell:{background:#8ec1da,color:#ffffff},tweets:{background:#ffffff,color:#444444,links: #1985b5}},特点:{滚动条:真,循环:真,住:真,行为: 默认}})渲染()开始();< \ /脚本>');。。
}

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



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

p>

 < form style =float:right;> 
< input type =text/>< input type =buttonvalue =Refreshonclick =refresh()/>
< / form>


解决方案

真的没有理由动态插入内联脚本标记成DOM元素。

 函数refresh(){
alert(按钮被按下);
新TWTR.Widget({版本:2,类型:搜索,搜索:#abbaseya,间隔:15000,
主题:小部件,宽度:300,高度:360,主题:{shell:{background:
#8ec1da,color:#ffffff},tweets:
{background:#ffffff,color:#444444,links:#1985b5 }},features:
{scrollbar:true,loop:true,live:true,behavior:default}})。render()。start();
返回false; //防止刷新
}


I'm trying to replace the contents of a div with other contents, both contents are JavaScript codes, however, when I press the button that calls the function, the whole page refreshes, and the new JavaScript in the function gets loaded onto the page (and looks corrupted too)

Here's my JavaScript function that I use

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>');
}

What am I doing wrong? tweet1 is just a div with an id, and the function above gets called by a button

here's the button I'm using, I have a form in the html

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

解决方案

There's really no reason to dynamically inject an inline script tag into a DOM element. Just execute the body of the script tag as regular JavaScript.

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
}

这篇关于把JavaScript放入jquery .html函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆