<a onclick="javascript:func(this)" >here</a>
thisस्क्रिप्ट में क्या मतलब है?
<a onclick="func(this)" >here</a>
<a onclick="javascript:func(this)" >here</a>
thisस्क्रिप्ट में क्या मतलब है?
<a onclick="func(this)" >here</a>
जवाबों:
जिस मामले के बारे में आप पूछ रहे हैं, thisवह HTML DOM तत्व का प्रतिनिधित्व करता है।
तो यह वह <a>तत्व होगा जिस पर क्लिक किया गया था।
यह DOM में उस तत्व को संदर्भित करता है जिससे onclickविशेषता संबंधित है:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
function func(e) {
$(e).text('there');
}
</script>
<a onclick="func(this)">here</a>
(यह उदाहरण jQuery का उपयोग करता है ।)
इवेंट हैंडलर विशेषताओं का मूल्य जैसे कि ऑनक्लिक केवल जावास्क्रिप्ट होना चाहिए, बिना किसी "जावास्क्रिप्ट:" उपसर्ग के। जावास्क्रिप्ट: छद्म-प्रोटोकॉल का उपयोग URL में किया जाता है, उदाहरण के लिए:
<a href="javascript:func(this)">here</a>
onclick="func(this)"हालाँकि आपको इसे प्राथमिकता के रूप में उपयोग करना चाहिए । यह भी ध्यान दें कि मेरे उदाहरण में जावास्क्रिप्ट का उपयोग करके ऊपर: छद्म-प्रोटोकॉल "यह" <a>तत्व के बजाय विंडो ऑब्जेक्ट को संदर्भित करेगा ।
जावास्क्रिप्ट thisमें एक्शन वाले तत्व को संदर्भित करता है। उदाहरण के लिए, यदि आपके पास कोई फ़ंक्शन है hide():
function hide(element){
element.style.display = 'none';
}
hideसाथ बुलाने thisसे तत्व छिप जाएगा। यह केवल क्लिक किए गए तत्व को लौटाता है, भले ही यह DOM के अन्य तत्वों के समान हो।
उदाहरण के लिए, आपके पास thisHTML में एक संख्या पर क्लिक हो सकता है नीचे क्लिक की गई बुलेट बिंदु को केवल छिपाया जाएगा।
<ul>
<li class="bullet" onclick="hide(this);">1</li>
<li class="bullet" onclick="hide(this);">2</li>
<li class="bullet" onclick="hide(this);">3</li>
<li class="bullet" onclick="hide(this);">4</li>
</ul>
यहां (यह) एक ऐसी वस्तु है जिसमें डोम तत्व की सभी विशेषताएं / गुण शामिल हैं। आप देख सकते हैं
console.log(this);
यह पदानुक्रम के साथ डोम तत्व के सभी गुण गुण प्रदर्शित करेगा। आप इसके द्वारा डोम तत्व में हेरफेर कर सकते हैं।
नीचे दिए गए लिंक पर भी वर्णन करें: -
addEventListener ईवेंट में इसे कीवर्ड करें
function getValue(o) {
alert(o.innerHTML);
}
function hide(current) {
current.setAttribute("style", "display: none");
}
var bullet = document.querySelectorAll(".bullet");
for (var x in bullet) {
bullet[x].onclick = function() {
hide(this);
};
};
/* Using dynamic DOM Event */
document.querySelector("#li").addEventListener("click", function() {
getValue(this); /* this = document.querySelector("#li") Object */
});
li {
cursor: pointer;
}
<ul>
<li onclick="getValue(this);">A</li>
<li id="li" >B</li>
<hr />
<li class="bullet" >1</li>
<li class="bullet" >2</li>
<li class="bullet" >3</li>
<li class="bullet" >4</li>
</ul>