簡體   English   中英

jQuery,單擊的元素屬性

[英]jQuery, clicked element properties

我該如何構建一個腳本,以獲取單擊元素的所有元素(如果設置了ID,NAME,CLASS,ELEMENT [div,form ...]的類型),請注意,我正在嘗試通過以下方式收集單擊元素的數據用戶。

 $('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> 

屬性是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> 

我寫這個小例子是為了您的目的。 另一個解決方案。 這樣,您可以查看所有單擊的對象屬性。 在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/

希望這可以幫助。

獲取this上點擊它會通過包你需要的所有信息

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM