当所有元素具有相同的类名时,如何获取被点击元素的id?

时间:2015-08-12 05:01:32

标签: javascript

我的代码就像这样

   config.action_mailer.smtp_settings = { 
   address: "smtp.gmail.com", 
   port: 587, 
   domain: Rails.application.secrets.domain_name, 
   authentication: "plain", 
   enable_starttls_auto: true, 
   user_name: Rails.application.secrets.email_provider_username, 
   password: Rails.application.secrets.email_provider_password 
   } 

如何知道点击哪一个以及如何获取所点击元素的ID和名称?

PS:我想稍后在javascript中编写代码,因为我要把代码放到GTM变量

3 个答案:

答案 0 :(得分:3)

使用Plain JS + html update:



NullPointerException

var info = function(dd) {
  alert(dd.id + ", " + dd.name);
};




使用Plain JS:



<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>
&#13;
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]);
&#13;
&#13;
&#13;

使用jQuery:

&#13;
&#13;
<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>
&#13;
$(function() {
  $('select.editable-input').on('click', function(e) {
    alert(this.id + ", " + this.name);
  });
});
&#13;
&#13;
&#13;

答案 1 :(得分:2)

如果您使用的是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);
   };
 }

答案 2 :(得分:2)

有一些方法可以做到这一点,但最好的方法是将一个单独的事件委托给你孩子的父母。

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>,它也会将事件委托给它。

Know more about event delegation

如果您不喜欢这种方法,您可以随时使用传统方法:

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
  });
}