[英]Is there a way to delete only clicked element when those elements all have the same ID?
[英]How to get id of the clicked element when all of the elements have the same class name?
我的代碼就像這樣
<select id="id_1" class="editable-input" name="name_1">
<select id="id_2" class="editable-input" name="name_2">
<select id="id_3" class="editable-input" name="name_3">
我如何知道哪一個被點擊以及如何獲取被點擊元素的ID和名稱?
PS:我想稍后用javascript編寫代碼,因為我要將代碼放到GTM變量中
使用Plain JS + html更新:
var info = function(dd) { alert(dd.id + ", " + dd.name); };
<select id="id_1" class="editable-input" name="name_1" onclick="info(this);"></select> <select id="id_2" class="editable-input" name="name_2" onclick="info(this);"></select> <select id="id_3" class="editable-input" name="name_3" onclick="info(this);"></select>
使用Plain JS:
var info = function(dd) { return function() { alert(dd.id + ", " + dd.name); } }; var dds = document.getElementsByClassName("editable-input"); for (var i = 0, l = dds.length; l > i; i++) dds[i].onclick = info(dds[i]);
<select id="id_1" class="editable-input" name="name_1"></select> <select id="id_2" class="editable-input" name="name_2"></select> <select id="id_3" class="editable-input" name="name_3"></select>
使用jQuery:
$(function() { $('select.editable-input').on('click', function(e) { alert(this.id + ", " + this.name); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <select id="id_1" class="editable-input" name="name_1"></select> <select id="id_2" class="editable-input" name="name_2"></select> <select id="id_3" class="editable-input" name="name_3"></select>
如果您使用的是jQuery,則可以使用以下命令:
$(".editable-input").on("click", function(e) {
var sender = $(this);
console.log(sender.prop("id"));
//OR
console.log(this.id);
});
如果您使用的是JavaScript:
var items = document.getElementsByClassName("example"),
currentItem;
for(var i = items.length; i--;) {
currentItem = items[i];
currentItem.onclick = function(e) {
console.log(this.id);
};
}
有一些方法可以做到這一點,但最好的方法是將一個單獨的事件委托給孩子的父母。
var div = document.getElementById("parent"); div.addEventListener("click", function(e) { var el = e.target; // here you can get el.id and el.name and do whatever you want if (el.tagName.toLowerCase() === "select") alert(el.id); });
<div id="parent"> <select id="id_1" class="editable-input" name="name_1"></select> <select id="id_2" class="editable-input" name="name_2"></select> <select id="id_3" class="editable-input" name="name_3"></select> </div>
這樣做,您只創建一個可以處理div中所有孩子的事件。 因此,您將使用更少的內存,即使您創建了另一個<select>
,但它已經將事件委托給它。
如果您不喜歡這種方法,您可以隨時使用傳統方法:
var sels = document.querySelecorAll(".editable-content");
for (var i = 0; i < sels.length; i++) {
sels[i].addEventListener("click", function(e) {
var el = e.target;
// here you can get el.id and el.name and do whatever you want
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.