Consider this HTML
<div id="container">
<ul id="someID">
<li id="someID1">
<div id="someID2">
<div class="someClass">
<label>labelText</label>
</div>
</div>
</li>
<li>2</li>
<li>3</li>
</ul>
</div>
and its script
<script>
$(function(){
$("#container label").click(function(){
$(this).text("labelTextChanged");
});
})
</script>
Let this code written by some one else. And Now I want to change the text labelTextChanged
to something new like labelTextChangedThen
(This is just an example, sometimes I would need to change a lot of functionality). But now its difficult to find the attached event from the DOM? How can I avoid these kind of problems while writing code in jQuery?
Is it a good approach to use only attributes (self defined attributes) for selecting elements? (as in Angularjs)
NB: In reality it may better or worse.
There are many ways to write clean(er) code. I prefer to separate my handler methods (using named functions) from the handling code, use data-attributes to query and use event delegation. For your example, the code could be rewritten to something like:
Where
<label>
would become<label data-changeOnClick="[changed text]">
In that case, changing the label text later would be as simple as changing the
data-changeOnClick
attribute in the html. Furthermore, it's easy to add the attribute to any element in your html, which will all trigger the click handler.Writing separate handler methods also shows the methods in the aforementioned 'visual event 2' bookmarklet.
Furthermore, I always load my scripting at the end of the document (right before the closing
</body>
-tag), to avoid having to wrap method assignment within$(function() {/*...*/} )
or more generally having to use document load-handling.See this jsFiddle