$("select[name=cmm]").change(function(){
total();
});
由于某种原因,没有使用上面的代码调用“total”函数。 html代码是:
<select name="cmm">
<option value="none">none</option>
<option value="one">the first</option>
<option value="two">the second</option>
</select>
我指的是错误的方式或元素?或者以错误的方式调用函数?
更新: 这里的警报功能没有出现,所以我猜测永远不会调用更改事件..
$(document).ready(function() {
$("select[name=cms]").change(function(){
total();
alert($("select[name=cms]").length);
});
});
(是的,我一直在使用doc-ready)
答案 0 :(得分:1)
有关更新的问题:
确保您的代码在document.ready
处理程序中运行,以便<select>
元素在DOM中并准备就绪,如下所示:
$(function() {
$("select[name=cmm]").change(function(){ total(); });
});
上一个问题:
你错过了选择器上的第二个m
,它应该是:
$("select[name=cmm]").change(function(){ total(); });
或更短:
$("select[name=cmm]").change(total);
对于第二个,只需直接在<select>
上使用.val()
即可获取值,如下所示:
var iets = $("select[name=cmm]").val();
//or when calling .change(total) like above, inside total you can use:
var iets = $(this).val();
当您指定option
时,无论选择了什么,它都会获得第一个 <option>
的值。
答案 1 :(得分:1)
我认为这不是cm
与cmm
问题,并且您可能过早地分配onChange
处理程序,这意味着DOM尚未初始化。
<script type='text/javascript'>//<![CDATA[
// if your javaScript is initialized before the actual
// select element liek this, it will not work
$("select[name=cm]").change(function(){
total();
});
function total() {
alert("works?");
}
</script>
//]]></script>
<select name="cm">
<option value="none">none</option>
<option value="one">the first</option>
<option value="two">the second</option>
</select>
你的javaScript应该在DOM准备好之后执行,所以你必须使用jQuery的document.ready事件,如下所示:
<script type='text/javascript'>//<![CDATA[
$(document).ready(function() {
$("select[name=cm]").change(function(){
total();
});
function total() {
alert("works?");
}
}
</script>
//]]></script>
<select name="cm">
<option value="none">none</option>
<option value="one">the first</option>
<option value="two">the second</option>
</select>
或者将它放在有问题的元素之后,如下所示:
<select name="cm">
<option value="none">none</option>
<option value="one">the first</option>
<option value="two">the second</option>
</select>
<script type='text/javascript'>//<![CDATA[
$("select[name=cm]").change(function(){
total();
});
function total() {
alert("works?");
}
</script>
//]]></script>
答案 2 :(得分:0)
我遇到了问题,因为我使用了一个插件来设置select元素的样式。 我的问题的解决方案(因为onchange函数不起作用)在这里: http://code.google.com/p/lnet/issues/detail?id=41