cod*_*olf 4 html javascript jquery onclick button
我有三个按钮,每个按钮chooseMap()功能onclick,然后根据按钮将用户重定向到新页面id.一切正常但我每次都要点击两次.谁能告诉我为什么会这样,以及我如何解决它?
<div class="row text-center" onclick="chooseMap();">
<div class="col-md-4">
<button type="button" class="btn btn-primary" id="world" >World Map</button>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary" id="europe">Europe</button>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary" id="sweden">Sweden</button>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
function chooseMap(){
$(document).ready(function() {
document.getElementById("sweden").onclick = function(){
location.href = "map_game/sweden.html";
}
document.getElementById("europe").onclick = function(){
location.href="map_game/europe.html";
}
document.getElementById("world").onclick = function(){
location.href="map_game/world.html";
}
})
}
Run Code Online (Sandbox Code Playgroud)
一切正常.我点击按钮,调用函数,传递正确的字符串,我很高兴地发送到下一页,一切都有效.但是,我必须在按钮上单击两次才能使其正常工作.我第一次点击没有任何反应.有什么想法吗?
Ror*_*san 10
问题是因为第一次单击执行该chooseMap函数,然后附加事件处理程序.然后第二次单击执行在这些事件处理程序中分配的代码.
要修复和改进代码,请删除内联onclick属性并使用jQuery附加事件.试试这个:
<div class="row text-center">
<div class="col-md-4">
<button type="button" class="btn btn-primary" id="world">World Map</button>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary" id="europe">Europe</button>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary" id="sweden">Sweden</button>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
$(document).ready(function() {
$("#sweden").click(function() {
window.location.assign('map_game/sweden.html');
});
$("#europe").click(function() {
window.location.assign('map_game/europe.html');
});
$("#world").click(function() {
window.location.assign('map_game/world.html');
});
});
Run Code Online (Sandbox Code Playgroud)
请注意,您甚至可以进一步通过使用DRY原则,你可以使用基于单处理器提高本class的的button元素,并使用设定的URL id按钮,这样的事情:
$(document).ready(function() {
$(".btn").click(function() {
window.location.assign('map_game/' + this.id + '.html');
})
});
Run Code Online (Sandbox Code Playgroud)