while exploring jQuery I came up with the following weird script. I don't see myself doing this really however concatenating strings to achieve a variable name is not unusual in JavaScript.
Any feedback welcome.
...
<script type="text/javascript">
var a = 'y';
$(document).ready(function() {
$('p[id^=' + $('p[id=x]').html() + a + "]").css('color','blue');
});
</script>
...
<p id="x">2a</p>
<p id="2ay_">mytext</p>
-
Short answer is no, there aren't side-effects. Your example is quirky, but as you said you were just exploring to see what you could do. I have used string concatenation and function value returns inside jQuery selectors before, it can be a useful technique for managing sets of related elements which reside in different parts of the DOM.
I admit I haven't used
jQuery.html()inside a selector, but there isn't any inherent reason why that's "bad". I just can't think of a situation where that'd be strictly necessary. It does make the code rather... unusual, and hence more difficult to understand and maintain.If you actually find a use for this in production code, please let us know. I'd be fascinated to see what it is. :)
Florin : Just wondering about some black magic in jQuery that would give unwanted side effects inside selectors. What I find myself needing is a to pass the 'search' string to the selector at runtime. Could by the way, jQuery do with this pattern: $('p[id=?]').click(paramValue, function() {}); ? -
In my opinion its unreadable, unmaintainable...anything like that should be avoided. Imagine you joined a new company and they put you in front of a whole bunch of js/jquery code that looked like that!!
P.S you should use addClass to change the color. I would rather change a css class after all it is a style setting and is also more extensible in that you can add other styles without any more js code.
-
No, nothing weird. Other than maybe some unwanted results if someone/you went and modified the HTML within the p element. It is definitely pretty weird the way it's coded, but nothing really wrong with it (other than being unreadable/unmaintainable).
Because jQuery is nothing special -- it's just a Javascript library. You aren't using some special JS syntax or anything, jQuery is simply taking a string and using it as a selector. So that string can be constructed any way you see fit.
-
Just wondering about some black magic in jQuery that would give unwanted side effects inside selectors. What I find myself needing is a to pass the 'search' string to the selector at runtime.
Could by the way, jQuery do with this pattern:
$('p[id=?]').click(paramValue, function() {}); where the paramValue replaces the placeholder '?' ?
-
Yep no reason you can't do this. Since
$is actually a function call itself anything that needs to be evaluated in order to pass a parameter to it is evaluated first.
0 comments:
Post a Comment