我有以下有效的代码 -
$(function(){
$('#testbutton').click(function(){
var checkedValue = $('[name="someRadioGroup"]:radio:checked').val();
$('#result').html('The radio element with value <tt>' + checkedValue + '</tt> is checked');
});
});
我知道 $('#testbutton') 获取带有 id testbutton 的 HTML 元素并为其分配一个事件处理程序。
但我不明白为什么我需要将该代码放在函数文字中?
如果我删除$(function(){
(和相应的});
)它不起作用。
但是,其他代码可以在不包含在函数文字中的情况下工作。例子 -
alert('Hi there')
有什么不同?为什么 alert 有效但事件赋值语句无效?