所以我有 2 個按鈕,當點擊它們時,它們會導致同一個視窗。但是,我希望能夠跟蹤按下了哪個按鈕,以便我可以在此基礎上做不同的事情,下面是我如何定義它們:
<div class = "buttons">
<button class = "worldBtn" onclick="window.location.href='map/map.html';">WORLD</button>
<br>
<button class = "usBtn" onclick="window.location.href='map/map.html';">UNITED STATES</button>
</div>
有什么辦法可以實作嗎?謝謝!
uj5u.com熱心網友回復:
使用 URL 查詢引數來區分它們。
<div class = "buttons">
<button class = "worldBtn" onclick="window.location.href='map/map.html?loc=world';">WORLD</button>
<br>
<button class = "usBtn" onclick="window.location.href='map/map.html?loc=us';">UNITED STATES</button>
</div>
然后在map.htmlJavaScript 中可以檢查window.location.search以確定使用了哪個按鈕。
uj5u.com熱心網友回復:
使用 $(this) 向按鈕添加一個相同的類,您將獲得它的值屬性。這是一個小代碼片段
$(".btn").click(function(e){
var title=$(this).attr("value");
alert(title);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class = "buttons">
<button class = "worldBtn btn" onclick="window.location.href='map/map.html';" value="WORLD">WORLD</button>
<br>
<button class = "usBtn btn" onclick="window.location.href='map/map.html';" value="UNITED STATES">UNITED STATES</button>
</div>
uj5u.com熱心網友回復:
您可以使用 click 事件來跟蹤哪個按鈕被點擊并采取相應的行動
HTML
<div class = "buttons">
<button id="btn1" class = "worldBtn">WORLD</button>
<br>
<button id="btn2" class = "usBtn">UNITED STATES</button>
</div>
使用 JQuery 的 JavaScript
$('#btn1').on('click', function(e) {
e.preventDefault();
console.log('worldBtn clicked');
window.location.replace("map/map.html");
})
$('#btn2').on('click', function(e) {
e.preventDefault();
console.log('usBtn clicked');
window.location.replace("map/map.html");
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334627.html
標籤:javascript html 查询 css
