[英]Javascript onclick() requires two clicks
我有三個按鈕,每個按鈕調用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>
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";
}
})
}
一切正常。 我點擊按鈕,調用函數,傳遞正確的字符串,我很高興地發送到下一頁,一切都有效。 但是,我必須在按鈕上單擊兩次才能使其正常工作。 我第一次點擊沒有任何反應。 有什么想法嗎?
問題是因為第一次單擊執行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>
$(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');
});
});
請注意,您甚至可以通過使用DRY原則進一步改進這一點,您可以使用基於button
元素class
的單個處理程序,並使用按鈕的id
設置URL,如下所示:
$(document).ready(function() {
$(".btn").click(function() {
window.location.assign('map_game/' + this.id + '.html');
})
});
使用jQuery進行事件處理,無論如何你都在使用它:
$(document).ready(function () {
$('#sweden').on('click', function () {
location.href = "map_game/sweden.html";
});
$('#europe').on('click', function () {
location.href = "map_game/europe.html";
});
$('#world').on('click', function () {
location.href = "map_game/world.html";
});
});
<div class="row text-center" onclick="chooseMap();">
<div class="col-md-4">
<a href="map_game/sweden.html"
><button type="button" class="btn btn-primary" id="world" >World Map</button></a>
</div>
<div class="col-md-4">
<a href="map_game/europe.html"><button type="button" class="btn btn-primary" id="europe">Europe</button></a>
</div>
<div class="col-md-4">
<a href="map_game/world.html"><button type="button" class="btn btn-primary" id="sweden">Sweden</button></a>
</div>
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.