jQuery,单击元素属性

时间:2016-08-06 12:14:09

标签: javascript jquery analytics

我怎么能建立一个脚本来获取点击元素的所有元素(如果设置ID,NAME,CLASS,TYPE OF ELEMENT [div,form ...]),请注意我正在尝试收集数据用户单击元素。

4 个答案:

答案 0 :(得分:1)



$('div').click(function(){
  console.log("ID: " +$(this).attr('id'));
  console.log("Class: " +$(this).attr('class'));
  console.log("Name: " +$(this).attr('name'));
  console.log("Type: " +$(this)[0].tagName);
});

.myclass{
  cursor:pointer;
  border:1px solid #333;
  width:100px;
  text-align:center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="mydiv" class="myclass">Click Me</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

Attributes是jQuery DOM对象的一个​​属性。对象包含每个属性的对象,并且可以从中拉出属性的名称和值。

$('body>*').click(function() {
  $('.cont').empty()
  // here you get element properties 
  $('.cont').append("tag --> " + this.tagName + "<br>")
 
  //here you get attributes 
  $.each(this.attributes, function() {
    // this.attributes is not a plain object, but an array
    // of attribute nodes, which contain both the name and value
 
    if(this.specified) {
      $('.cont').append(this.name + ' --> ' + this.value + '<br>');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="A" id ="2" markup = "html" something="beacon">A</div><br>
<button class="B" id ="10" markup = "xml" something="beacon">B</button><br>
<span class="C" id ="23" markup = "aa" something="beacon">C</span><br>
<div class="D" id ="19" markup = "cc" something="beacon">D</div><br>

<br>
<br>


<div class="cont">
  
  
</div>

答案 2 :(得分:1)

我为你的目的写了这个小例子。又一个解决方案。 通过这种方式,您可以查看所有单击的对象属性。在html中:

<input type="button" value="Click me"/>
<a href="#">click me</a>

在JavaScript中:

$("body").on("click", "*", function(event) {
  var allProps = [];
  var obj = this;
  while(Object.getPrototypeOf(obj)) {
      allProps = allProps.concat(Object.getOwnPropertyNames(obj));
      obj = Object.getPrototypeOf(obj);
  }
  console.log(allProps);
  event.preventDefault();
});

这是工作jsFiddle:

https://jsfiddle.net/zu5pe699/14/

希望这会有所帮助。

答案 3 :(得分:0)

获取this点击它将包含您需要的所有信息

 $('#clickMe').on('click',function(){
  console.log(this);
 });