jQuery Prototype Chain
In this page:
$.fn.methodName = function () {
return this;
};
$.fn क्या है?
$.fn वह object है जिसे jQuery हर jQuery-wrapped selection के लिए prototype की तरह इस्तेमाल करता है, यही वजह है कि $.fn में एक method add करना उसे उपलब्ध बना देता है।
उदाहरण: What is $.fn?
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p>Text</p>
<script>
$.fn.shout = function() {
return this.text($(this).text().toUpperCase());
};
$("p").shout();
</script>
</body>
</html>
Chaining के लिए this Return करें
एक plugin को आमतौर पर selected elements बदलना खत्म करने पर this return करना चाहिए, क्योंकि this उस jQuery object को refer करता है जिस पर method call किया गया था।
उदाहरण: Return this for Chaining
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p>Text</p>
<script>
$.fn.highlight = function() {
return this.css("background", "yellow");
};
$("p").highlight().css("padding", "10px");
</script>
</body>
</html>
कई Elements के साथ काम करना
एक jQuery plugin को आमतौर पर current selection के हर element पर operate करना चाहिए, सिर्फ पहले पर नहीं, क्योंकि $(...) कई elements से match कर सकता है।
उदाहरण: Work with Multiple Elements
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p>One</p><p>Two</p>
<script>
$.fn.shout = function() {
return this.each(function() {
$(this).text($(this).text().toUpperCase());
});
};
$("p").shout();
</script>
</body>
</html>
Plugin Scope को Safely इस्तेमाल करना
Plugin code को unnecessary global variables बनाने से बचना चाहिए, क्योंकि वे उसी page पर दूसरे scripts के साथ silently collide कर सकते हैं। एक plugin को wrap करना।
उदाहरण: Use Plugin Scope Safely
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<script>
(function($) {
$.fn.highlight = function() {
const privateColor = "yellow";
return this.css("background", privateColor);
};
})(jQuery);
</script>
</body>
</html>
एक छोटा Prototype Project
यह prototype pattern — $.fn में functions attach करना जो chaining के लिए this return करते हैं — jQuery में नए chainable methods add करने का standard, expected तरीका है।
उदाहरण: Small Prototype Project
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<p>Text</p>
<script>
$.fn.highlight = function() {
return this.css("background", "yellow");
};
$("p").highlight();
</script>
</body>
</html>
- एक plugin को
$.fnके बजाय$में add करना, ताकि$("p").myPlugin()एक function न हो। - plugin के अंत में
return this;भूल जाना, जो$("p").myPlugin().hide()जैसी chaining तोड़ देता है। - plugin method के लिए एक arrow function इस्तेमाल करना, जहाँ
thisअब jQuery selection को refer नहीं करता।
Chapter Quiz — Complete all 4 topics to unlock
0/4 topics done
Complete these topics first: