我讀過通過變量通過jQuery訪問對象或集合比通過內聯代碼重複訪問它們要高效得多。即使是在一個簡單的測試,但這似乎是正確的:jQuery,變量和單選按鈕
<!doctype html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<script src="/jquery-1.5.1.js"></script>
<script>
var SomeChoiceRadios;
$(document).ready(function(){
SomeChoiceRadios = $("#MyForm input:radio[name='SomeChoice']");
});
function DoStuff()
{
console.profile('Optimized');
for (i=0; i < 10000; i++)
foo = SomeChoiceRadios.filter(":checked").val();
console.profileEnd();
}
function DoStuff2()
{
console.profile('Inline');
for (i=0; i < 10000; i++)
foo = $("#MyForm input:radio[name='SomeChoice']:checked").val();
console.profileEnd();
}
</script>
<form id="MyForm" name="MyForm">
<input type="radio" name="SomeChoice" value="0">0<br>
<input type="radio" name="SomeChoice" value="1">1<br>
<input type="radio" name="SomeChoice" value="2">2<br>
<input type="radio" name="SomeChoice" value="3">3<br>
<input type="radio" name="SomeChoice" value="4">4<br>
<input type="radio" name="SomeChoice" value="5">5<br>
<input type="button" value="Time" onclick="DoStuff()">
<input type="button" value="Time" onclick="DoStuff2()">
</form>
</body>
</html>
鑑於上面的例子中,有沒有更快捷的方式來獲得SomeChoice
檢查單選按鈕的值,如果我試圖訪問它使用變量(即SomeChoiceRadios
)?
謝謝您的信任投票。我只是想確保我沒有錯過任何東西。 – 2011-04-07 15:39:45