【发布时间】:2013-11-23 00:43:58
【问题描述】:
默认情况下,我希望任何具有“.options”类的按钮执行与警报(“Hello World”)相同的操作。如果您往下看,您会看到另一个按钮,其 id 名称为“append_another_content”。它的工作是附加另一个<input type="button" class=".options" value="Option"> 并使其执行与其余“.options”按钮相同的操作。但是,除非我再次调用 myFunction(),否则刚刚添加的按钮不会执行任何操作,现在的问题是,一旦我再次调用 myFunction(),一旦添加了新内容,之前的按钮就会带有类 '.options'将根据您按下“附加”按钮的次数重复调用 myFunction()。我的目标是,每次单击“.options”按钮时只调用一次 myFunction()。
<html>
<head></head>
<body>
<div id="wrap">
<input type="button" class=".options" value="Option">
<input type="button" class=".options" value="Option">
<input type="button" class=".options" value="Option">
<input type="button" class=".options" value="Option">
</div>
<input type="button" id="append_another_content" value="Append"/>
</body>
<script>
function myFunction(){
$('.options').click(function(){
alert('Hello Friends!');
});
}
//By default I want any buttons with a class '.options' to perform the same actions which is to alert('Hello World')
myFunction();
$('#append_another_content').click(function(){
$.ajax({
type: 'POST',
url: 'ajax/get_another_button.php',
}).done(function(data){
$('#wrap').append(data);
//The data will just return '<input type="button" class=".options" value="Option">'
//The button that has just been appended will not perform any action unless I call myFunction()
myFunction();
});
});
</script>
</html>
【问题讨论】:
标签: javascript jquery function func