我是JQuery的新手我曾尝试在stackoverflow中阅读其他解决方案,但我还不了解它。请你帮助我好吗?
调用函数addQuestion后,我有一个附加到页面上的按钮。当我单击按钮时,它不起作用,但在html中创建具有相同ID的按钮确实有效。
<!DOCTYPE html>
<html>
<head>
<title>Javascript</title>
</head>
<body>
<div id="header">
<h1>My Site</h1>
</div>
<div id="content">
<p ><h2>Question: </h2></p>
<strong>question 1:</strong> how old am I? <br>
a) 18 <br>
b) 17 <br>
c) 22 <br>
<br>
<input id="myAnswer" type="text">
<button id="addOne">answer</button>
</div>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"> </script>
<script>
$('#addOne').click(function() {
var theAnswer = $('#myAnswer').val();
alert(theAnswer);
});
function addQuestion(questionNo, task, reply){
$('#content').append("<br><br><br>" + questionNo + task + "<br>" + reply + "<br>"
+ '<input id="myAnswer" type="text">' + '<button id="addOne">answer</button>' );
}
addQuestion("<strong> question 2: </strong>", "what's my name", "a) Will <br> b) Peter <br> c) Jeff " );
</script>
</body>
</html>
&#13;
答案 0 :(得分:1)
首先使用类而不是该按钮的ID。其次,您需要一个面向未来的事件监听器。第三,命名您的组件,以便有一些上下文绑定:
// Notice we map the answer to the button with a data attribute.
function addQuestion(id, questionNo, task, reply){
$('#content').append("<br><br><br>" + questionNo + task + "<br>" + reply + "<br>"
+ '<input id="myAnswer-' + id + '" type="text">' + '<button class="addOne" data-answer-id="myAnswer-' + id + '">answer</button>' );
}
// Notice we bind click on the static container and delegate to a dynamic element.
$('#content').on('click', '.addOne', function() {
var theAnswer = $('#' + $(this).data('answer-id')).val();
alert(theAnswer);
});
// Example add - pass in 2 for an ID
addQuestion(2, "<strong> question 2: </strong>", "what's my name", "a) Will <br> b) Peter <br> c) Jeff " );
答案 1 :(得分:0)
当您的按钮被动态添加时,您需要使用jQuery.on()将事件处理程序附加到新创建的按钮,并且ID应该是唯一的,因此请确保在生成多个按钮时使用不同的id:< / p>
$(document).ready(function() {
$(document).on('click', '#addOne', function() {
var theAnswer = $('#myAnswer').val();
alert(theAnswer);
});
});
答案 2 :(得分:-1)
嗨,问题是你不能拥有两个ID相同的按钮。 您可以创建两个不同的按钮..并创建一个新脚本。
<script>
$('#addOne').click(function() {var theAnswer = $('#myAnswer').val();alert(theAnswer);});
$('#addTwo').click(function() {var theAnswer = $('#myAnswer2').val();alert(theAnswer);});
function addQuestion(questionNo, task, reply){$('#content').append("<br><br><br>" + questionNo + task + "<br>" + reply + "<br>"+ '<input id="myAnswer2" type="text">' + '<button id="addTwo">answer</button>' );};
addQuestion("<strong> question 2: </strong>", "what's my name", "a) Will <br> b) Peter <br> c) Jeff ");
</script>
或者使用类和&#34;这个&#34;字。