我试图让这项工作从很长一段时间开始,但似乎无法做到 - 我的x.html-
<div class="col-lg-2 col-lg-offset-4">
<a href="#add" id="addform" role="button" class="btn btn-info pull-right" data-toggle="modal" style="margin-top:20px">Add Contract</a>
</div>
{% include "a_bs3.html" with form_title="Add :" form_btn="Add" form_id="add" ajax="True" %}
<script>
$(document).ready(function() {
var check = location.hash;
if (check == "trigger") {
//button trigger even though you do not click on it
$('#addform').click();
}
});
</script>
我试图触发这个'添加:'表格按钮,只要网址包含值“触发器”但按钮不是自动点击,我做错了什么? 如果您手动点击“添加:”,表单就会正常打开。
答案 0 :(得分:2)
用户jquery trigger
功能。 click
函数用于覆盖click事件。那不是你想要的。要手动触发事件,请使用trigger。
$(document).ready(function() {
var check = location.hash;
if (check == "#trigger") {
//triggering click event on #addform
$('#addform').trigger('click');
}
});
示例代码
$(document).ready(function() {
$("#clickME").click(function(){alert("clicked");});
$("select").change(function(){
if($(this).val() == 3){
$('#clickME').trigger('click');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br/>
<h4>Clickable button</h4>
<button id="clickME">clickME</button>
<br/>
<h4>Select box.When 3 is selected, the click event will trigger</h4>
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
答案 1 :(得分:0)
我创建了一个模块化设计,使您能够使用DOM ID更新handler
对象,并获得无限量的按钮,每个按钮都没有条件
//key: the button id, value: a callback function
// this enables us the reuse functions outside the button scope.
const handlers = {
foo: () => {
alert("foo")
},
bar: () => {
alert("bar")
},
baz: () => {
alert("baz")
}
}
//bunding all our [data-actionable] buttons automatically
let $buttons = $("[data-actionable]");
$buttons.each((i, button) => {
$(button).on("click", handlers[button.dataset.actionable]);
})
//triggering the handler on change, regardless of the buttons - seperation of concerns.
$(".select").on("change", (e) => {
let target = e.currentTarget;
handlers[target.value].apply(null);
});
&#13;
.button {}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" id="foo" data-actionable="foo">foo</button>
<button class="button" id="bar" data-actionable="bar">bar</button>
<button class="button" id="baz" data-actionable="baz">baz</button>
<select class="select">
<option>choose something...</option>
<option value="foo">foo</option>
<option value="bar">bar</option>
<option value="baz">baz</option>
</select>
&#13;