【问题标题】:jQuery createElement("script") issuejQuery createElement("script") 问题
【发布时间】:2013-07-08 09:23:31
【问题描述】:

我使用document.createElement("script"); 在我的html 头部生成带有一些代码的脚本标签,点击按钮。完整代码:

    //dynamic
$(document).ready(function() {


var AddButton       = $("#AddMoreBox"); //Add button ID

var FieldCount=0; //to keep track of text box added

var s = document.createElement("script");

$(AddButton).click(function (e)  //on add input button click
{
        FieldCount++; //text box added increment

        s.type = "text/javascript";
        s.text= '$(function(){alert('+ FieldCount +')});';

        $("head").append(s);

        x++; //text box increment
return false;
});

});

我注意到每次单击按钮时,head 中生成的脚本都会被更大的数字替换。是否有某种方法可以避免它们被替换,但在它的生成上,之前生成的脚本会保留下来,而新的脚本会出现在前面,例如落后于之前的脚本?

我不知道为什么,我的警报在第二次创建脚本后没有显示。我错过了什么还是什么?

这是 jsfiddle 的情况:http://jsfiddle.net/dzorz/6F7jR/

【问题讨论】:

    标签: jquery dynamic createelement


    【解决方案1】:

    http://jsfiddle.net/N79tH/

    您已在单击处理程序之外声明了您的脚本元素,因此它正在被重用,将var s 声明移动到处理程序内以获得您想要的效果。像这样:

    $(document).ready(function () {
    
        var AddButton = $("#AddMoreBox"); //Add button ID
        var FieldCount = 0; //to keep track of text box added
    
        $(AddButton).click(function (e) //on add input button click
        {
            var s = document.createElement("script");
            FieldCount++; //text box added increment
            s.type = "text/javascript";
            s.text = '$(function(){alert(' + FieldCount + ')});';
            $("head").append(s);
            x++; //text box increment
            return false;
        });
    
    });
    

    【讨论】:

      【解决方案2】:

      试试这个

      http://jsfiddle.net/6F7jR/2/

      //dynamic
      $(document).ready(function() {
      
      
      var AddButton       = $("#AddMoreBox"); //Add button ID
      
      var FieldCount=0; //to keep track of text box added
      
      
      
      $(AddButton).click(function (e)  //on add input button click
      {
          var s = document.createElement("script");//use here because every time create new element
              FieldCount++; //text box added increment
      
              s.type = "text/javascript";
              s.text= '$(function(){alert('+ FieldCount +')});';
      
              $("head").append(s);
      
              //x++; //text box increment because x is not defined
      return false;
      });
      
      });
      

      【讨论】:

        猜你喜欢
        • 2011-08-04
        • 1970-01-01
        • 2016-04-02
        • 2011-06-28
        • 2018-11-27
        • 2014-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多