我在div中包含了一个按钮。 问题是,如果我单击按钮,则会以某种方式从div而不是按钮触发click功能。
这就是我对点击事件的功能:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
}
这就是我的HTML(在动态创建之后!!):
<div id="ButtonDiv">
<div class="Line1" id="Line1Software">
<button class="Line1" id="Software">Test</button>
</div>
</div>
所以现在来自click函数的myVariable是'Line1Software',因为事件是从div而不是按钮触发的。
我的点击功能看起来像这样,因为我正在动态创建按钮。
修改
这就是我创建按钮并将它们包装在div
中的方法var c = $("<div class='Line1' id='Line1Software'</div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
答案 0 :(得分:0)
真正的问题是,{% extends "layout.html" %}
{% block title %}
Quote
{% endblock %}
{% block main %}
<form action="{{ url_for('quote') }}" method="post">
<fieldset>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="symbol" placeholder="symbol" type="symbol"text"/>
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Search for Quote</button>
</div>
</fieldset>
</form>
{% endblock %}
和div
都没有button
。
您使用示例html的代码实际触发两次,每个元素一次,因为事件将冒泡并匹配两个元素(因为它们是id
)
如果您只想让它与最里面的元素匹配,那么使用.Line1
来阻止冒泡。
return false
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
console.log(myVariable);
return false;
});
var c = $("<div class='Line1' id='Line1Software'></div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
答案 1 :(得分:0)
您使用示例html的代码实际触发两次,每个元素一次,因为事件将冒泡并匹配两个元素(因为它们是.Line1)
答案 2 :(得分:0)
如果您尝试向该按钮添加事件监听器,则应该使用$('#ButtonDiv')
而不是{{1}}
答案 3 :(得分:0)
你的问题有点奇怪,因为你给自己答案了......看看你的代码,你明确地使用事件委托:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
});
此代码表示,对于.Line1
元素的每次点击,该事件将委派给#ButtonDiv
元素(感谢冒泡)。
如果您不想要此行为,请执行以下操作:
$('.Line1').on('click', function () {
var myVariable = this.id;
});
这也是正确的:
$('.Line1').click(function () {
var myVariable = this.id;
});