您好,我对编码有点陌生,所以如果我不理解您使用的一些术语,请耐心等待。
所以基本上我有 2 个按钮,其功能是添加和删除按钮。添加按钮后,该按钮的功能就是显示用户的位置。
目前,按最后一个按钮删除按钮。我如何选择删除特定按钮?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<style>
button{
height:100px;
width: 80px;
text-align: center;
margin: 5px 4px;
}
#mainButtons button{
display: inline-block;
margin: auto;
}
</style>
<div id="mainButtons">
<button onclick="addButton()">Add Contact</button>
<button onclick="removeButton()">Remove Contact</button>
</div>
</br>
<div id="que"></div>
<script>
var increment = 0;
function addButton(){
var id = 'btn' + (increment++);
var que = $("#que");
var el = $("<button id='"+id+"'>Click for location</button>");
que.append(el);
clickHandler(el);
}
function removeButton(){
if (increment >= 0) {
$("#btn"+(increment-1)).remove();
increment--;
}
}
function clickHandler(el) {
el.click(function() {
getLocation(el);
});
}
function getLocation(el) {
el.html("Loading....");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) { showPosition(el, position); });
} else {
el.html("Geolocation is not supported by this browser.");
}
}
function showPosition(el, position) {
el.html("Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude);
}
</script>
</body>
</html>
最佳答案
你可以通过多种方式做到这一点,这就是我设法做到的。
var increment = 0;
function addButton(){
var id = 'btn' + (increment++);
var que = $("#que");
var el = $(`<button id='${id}'>Click for location(id:${id})</button>`);
que.append(el);
clickHandler(el);
}
function removeButton(id){
if (increment >= 0) {
$(`button#${id}`).remove();
}
}
function clickHandler(el) {
el.click(function() {
getLocation(el);
});
}
function getLocation(el) {
el.html("Loading....");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) { showPosition(el, position); });
} else {
el.html("Geolocation is not supported by this browser.");
}
}
function showPosition(el, position) {
el.html("Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude);
}
document.getElementById('removeButton').addEventListener('click',function(){
var input = $('#inputWithId')
var buttonIdToDelete = input?input.val():null
removeButton(buttonIdToDelete)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainButtons">
<button onclick="addButton()">Add Contact</button>
<button id="removeButton">Remove Contact</button>
<label for="inputWithId">Button id:</label>
<input id="inputWithId" />
</div>
</br>
<div id="que"></div>
关于javascript - 如何删除特定按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45767260/