如何将JS呈现给使用JS生成的内容?

时间:2013-01-05 14:13:05

标签: javascript jquery jquery-ui

  

可能重复:
  Executing <script> elements inserted with .innerHTML

我遇到问题,使用Java Script生成内容时,嵌入式脚本无法运行。如何正确编码?

这是一个工作示例: class datepicker适用于静态html代码,但不适用于使用添加新行按钮在运行时添加的那些行。 Plesae注意,重新加载页面对我来说不是一个选项,因为真正的问题更复杂。

感谢您的帮助。

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
    <link rel="stylesheet" href="/resources/demos/style.css" />
    <script>
    $(function() {
        $( ".datepicker" ).datepicker({
        yearRange: "-100:+0",
            changeMonth: true,
            changeYear: true,
            dateFormat: 'yy-mm-dd'
        });
    });
    </script>
</head>
<body>

<p>How many children do you have? What is their names and age?</p>
 <input type="text" id="qchildren" />
 <div id="qchildren-answer-wrapper"></div>


<button type="button" onclick="addNew()">Add new entry</button>
<button type="button" onclick="save()">Save</button>

 <br/>This is a correct date picker:
 <input type="text" class="datepicker" id="dp1" />

<script>
var lines=0;
function addNew()
{
lines++;
var newElement = document.createElement("span");
  newElement.innerHTML =  'Name:<input type="text" id="qchildrenname'+window.lines+'" /> Birth date:<input type="text" class="datepicker" id="qchildrenage'+window.lines+'" /><br/>';
document.getElementById("qchildren-answer-wrapper").appendChild(newElement);
}

function save()
{
var answer='';
for (var ii=1;ii<=window.lines;ii++)
{
if (document.getElementById('qchildrenname'+ii.toString()).value.toString()!=''){
answer+=document.getElementById('qchildrenname'+ii.toString()).value.toString()+','+document.getElementById('qchildrenage'+ii.toString()).value.toString()+';';
}
}
document.getElementById("qchildren").value=answer;
}
</script>


</body>
</html>

1 个答案:

答案 0 :(得分:1)

第一个将datepicker与你的html输入联系起来的抽象函数:

<script>
function attachDatePickerById(id) {
    $( "#" + id ).datepicker({
    yearRange: "-100:+0",
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd'
    });
}

// Attaching your initial datepicker with id "dp1"
$(attachDatePickerById("dp1"));
</script>

然后在连接后为每个新的日期选择器调用此函数:

function addNew()
{
    lines++;
    var newElement = document.createElement("span");
    newElement.innerHTML =  'Name:<input type="text" id="qchildrenname'+window.lines+'" /> Birth date:<input type="text" class="datepicker" id="qchildrenage'+window.lines+'" /><br/>';
    document.getElementById("qchildren-answer-wrapper").appendChild(newElement);

    // Tie jquery datepicker control to new added html INPUT
    attachDatePickerById("qchildrenage" + window.lines);
}