Can I write this javascript more efficiently with jquery?
Do you think jquery could help me get the following script work faster? Thanks!
window.onload=function colorizeCheckedRadios(){
var inputs = document.getElementsByTagName("input");
if (inputs) {
for (var i = 0; i < inputs.length; ++i) {
if(inputs[i].checked&&inputs[i].type=="radio"){
inputs[i].parentNode.parentNode.style.backgroundColor='#FCE6F4';
}
}
开发者_StackOverflow社区 }
}
Faster, I don't know. Cleaner and cross browser: yes
$(function() {
$('input:radio:checked').parent().parent().css('background-color', '#FCE6F4');
});
No, because jQuery will parse jQuery selectors used in the code, so it will be slower.
You can do this version with jQuery:
$(function() {
$(":radio:checked").parent().parent().css('background-color', '#FCE6F4');
});
So, yes, you can slim it down a bit :)
If you knew what the parent you wanted was, say a <span>
, you can do this:
$(function() {
$(":radio:checked").closest('span').css('background-color', '#FCE6F4');
});
Yes, probably. jQuery has the jQuery.ready() method which executes the function when the DOM is complete, and not when all the images are loaded. See: http://15daysofjquery.com/quicker/4/
If you have a named ancestor element that can help you exclude most of the rest of the web page starting there will greatly speed up your selector.
... tons of html
<div id="radioButtonList">
... the various radio button divs or what nots
</div>
... tons more html
$(function() {
$("#radioButtonList :radio:checked").parent().parent().css('background-color', '#FCE6F4');
});
精彩评论