0

可能重复:
执行插入 .innerHTML 的 <script> 元素

我有一个问题,当使用 Java 脚本生成内容时,嵌入式脚本不起作用。如何正确编码?

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

谢谢你的帮助。

<!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>
4

1 回答 1

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);
}
于 2013-01-05T15:00:02.893 回答