javascript - 使用jquery创建id失败

标签 javascript jquery html

我正在创建动态 mcq 问题,但现在在获取文本框的 ID 时遇到问题。我使用 jquery 测试 id,如下所示

<html>
<head>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>

<body>
<script type="text/javascript">
var counter1 = 1;//mcq
var counter = 2;//question
$(document).ready(function(){

$("#Q2choice1").click(function (){
    alert ("dsa");
});

$("#addQuestion").click(function () {

var newTextBoxDiv = $(document.createElement('div'))
     .attr("id", 'TextBoxDiv' + counter);

newTextBoxDiv.after().html('<label>Q'+ counter + ' : </label>' +
      '<input type="text" name="textbox' + counter + 
      '" id="textbox' + counter + '" value="" >' + '</br>' + 
      '<input type="radio" onclick="disable(this);" />'+
      '<input type="text" id="Q'+counter+'choice1" placeholder="Option' + counter1 +' Q'+ counter +'" ">' +
      '<input type="button" value="Add Option" id="Q'+ counter +'">');

newTextBoxDiv.appendTo("#TextBoxesGroup");
alert(counter);
counter++;
 });

 $("#removeQuestion").click(function () {
if(counter==1){
      alert("No question that can be deleted");
      return false;
   }   

counter--;

    $("#TextBoxDiv" + counter).remove();

 });

 //$("#getButtonValue").click(function () {

// var msg = '';
//for(i=1; i<counter; i++){
 // msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
//}
//      alert(msg);
 //});
});

function disable(element){
element.checked=false;
}

</script>


</head>

这是 html

<body>

<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
    <label>Q1 : </label><input type='textbox' id='textbox1' ></br>
    <div id="optionList1">
    <input type='radio' onclick="disable(this);" /> <input type='text' id='Q1choice1' value='' placeholder='option1Q1'>
    <input type='button' value='Add Option' name='1' class="inner" id='Q1'>
    </div>
</div>
</div>
<input type='button' value='Add Question' id='addQuestion'>
<input type='button' value='Remove Question' id='removeQuestion'>

</body>
</html>

我使用点击功能并使用警报来确保 id 存在。问题是当我创建下一个问题并输入

$("#Q2choice1").click(function() 

它不发出警报,这意味着我的 ID 不存在。我的jquery有什么问题?

最佳答案

.click() 未应用,因为 $("#Q2choice1") 尚不存在。使用 .on() ( http://api.jquery.com/on/ ) 的事件委托(delegate)版本来确保附加监听器。

替换:

$("#Q2choice1").click(function (){
    alert ("dsa");
}); 

与:

$('body').on('click', '#Q2choice1', function () {
     alert("DSA");
});

通过将监听器应用到 body 元素,您可以确保它被附加。然后,您可以委托(delegate)给任何您想要的元素,无论它是否存在。

示例:http://jsfiddle.net/hr7nR/

关于javascript - 使用jquery创建id失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19978402/

相关文章:

php - 键入内容后,值会出现在文本框中

javascript - 如何在事件处理程序中过滤掉子元素事件?

javascript - 根据选择打印值

javascript - 更快的 HTML5 视频替代方案

jquery - 使用 jQuery 更改不同域上 iframe 的文本框值?

javascript - 无法动态创建和附加 div 和 span

jquery - 在 jQuery 序列化为数组后删除选定的键和值

javascript - 我如何在 IE9、iOS 上验证所需的 jqBootstrapValidation

php - jquery 与 PHP mySQL 聊天

javascript - ActionScript 3中的链接按钮+ jQuery集成中的淡出