2016-08-06 5 views
0

クリックした要素のすべての要素(ID、名前、クラス、種類の要素[div、form ...])を取得するスクリプトを作成するにはどうすればいいですか?ユーザーがクリックした要素のデータを収集しようとしています。jQuery、要素のプロパティをクリックしました

+1

'.on()'を使用してドキュメントレベルで委任されたクリックハンドラを作成します。クリックハンドラの中では 'this'が要素になるので、' this.id'、 'this.name'、this.className'などで何をしたいのですか? – nnnnnn

+2

' jQuery( "*" ).on( "click"、function(){console.log(this)}) 'はユーザーがクリックする情報を記録します。 – vlaz

+0

@Vldユーザーが要素をクリックするとうまくいかず、おそらく要素>親>本文> htmlを記録します –

答えて

0

それは

$('#clickMe').on('click',function(){ 
    console.log(this); 
}); 
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>

1

属性あなたに必要なすべての情報をラップしますクリックでthisを取得は、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>

+0

'this.id'と' this.name'が(nameプロパティを持つ要素の)idとnameをすでに与えているときに、なぜ 'this.attributes'が必要なのですか?他のプロパティと同様です。 – nnnnnn

+0

'$(element).markup'(例えば)は' undefined'プロパティです。私は現在の属性の名前が必要です。 –

+0

そして、私は要素属性ではないhtml属性を参照しています –

1

私はあなたの目的のために、この小さな例を書きます。さらに別の解決法。 このようにして、クリックされたすべてのオブジェクトのプロパティを表示できます。 JavaScriptで

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

:HTMLで

$("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/

は、この情報がお役に立てば幸いです。

関連する問題