vbscript / javascript 中不会发生动态事件函数绑定
按钮 1 工作正常,但是当我尝试动态插入按钮 2 时,onclick 事件不会调用其映射函数,有任何线索它是如何工作的吗?这是一个简单的示例,但稍后我需要从复杂对象(例如轨迹栏的滚动事件)捕获事件。
<html>
<head>
<title>a simple first page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form").append("<input id='button2' type='button' value='button 2'>");
});
</script>
<script language="vbscript">
Sub Button1_OnClick()
MsgBox "button 1"
End Sub
Sub Button2_OnClick()
MsgBox "button 2"
End Sub
</script>
</head>
<body>
<form id="form"><input id="button1" type="button"
value="button 1"></form>
</body>
</html>
Button 1 works fine, but when I try to insert button 2 dynamically the onclick event doesn't call its mapped function, any clue how it works? This is a simple example but later I need to capture events from complex object like trackbar's scroll event.
<html>
<head>
<title>a simple first page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form").append("<input id='button2' type='button' value='button 2'>");
});
</script>
<script language="vbscript">
Sub Button1_OnClick()
MsgBox "button 1"
End Sub
Sub Button2_OnClick()
MsgBox "button 2"
End Sub
</script>
</head>
<body>
<form id="form"><input id="button1" type="button"
value="button 1"></form>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果要向 DOM 动态添加新按钮,请使用 jquery 的
live()
函数:这会将事件添加到所有当前 DOM 元素和“尚未”创建的元素!
If you are adding a new button to the DOM dynamically use the
live()
function of jquery:That'll add events to all current DOM elements and 'yet' to be created ones!
我不确定 VB 脚本,但是,您可以使用 jQuery live 函数将处理程序附加到任何按钮,或者在创建输入并附加到表单时在 onclick 事件上分配函数。
参见示例
I am not sure about VB script but this, you can attach a handler to any your button using jQuery live function or by assigning function on onclick event while creating your input and appending to form.
see example
如何
Button1_Click
被调用? IE 中是否存在某种我不知道的隐式绑定?我的方法是使用attachEvent()
添加事件。IE 不允许 onClick 事件动态创建 DOM 'a' 元素
How does
Button1_Click
get called at all? Is there some sort of implicit binding in IE, that I don't know about? The way I'd do it is to add an event withattachEvent()
.IE not allowing onClick event on dynamically created DOM 'a' element