Вопрос

I'm using document.createElement("script"); for generation of script tag with some code in head of my html, on click of button. Whole code:

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

});

I've noticed that everytime I click the button generated script in head gets replaced with that of bigger number. Is there some way that they don't get replaced but on it's generation the previous generated script stays and new one get in head for example behind previous?

And I don't know why, my alerts does not show after second created scripts. Am I missing something or what?

Here is jsfiddle with situation: http://jsfiddle.net/dzorz/6F7jR/

Это было полезно?

Решение

http://jsfiddle.net/N79tH/

You have declared your script element outside your click handler, so it is being reused, Move the var s declaration inside the handler to get the effect you want. Like so:

$(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;
    });

});

Другие советы

try this

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

});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top