Internet Explorer 8获得Radiobutton的价值

时间:2013-03-20 23:14:10

标签: javascript jquery internet-explorer internet-explorer-8

我一直在谷歌搜索大约2个小时来解决以下问题(包括其他Stackoverflow问题):

<script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery('input[type="radio"]').unbind('click.preset')
        .bind('click.preset', function() {
            doingStuffWith(jQuery(this).val());
        });
    });
</script>

<input type="radio" name="lightType" value="led" />
<input type="radio" name="lightType" value="tube" />

正如您所看到的,我只是想要检索单选按钮组“lightType”的当前值以使用它。这就像Firefox / Safari / Chrome中的魅力一样,但IE8只是返回一个空字符串给我带来了困难。

我已经尝试过其他一些问题,例如将更改事件绑定到单选按钮,并强制IE8通过模糊点击的单选按钮等来触发它。也许我是 现在只是患有失明。

我正在使用最新的jQuery版本,我确保没有其他绑定事件干扰。有趣的是,在检索值之前添加alert()并且IE返回当前值:

....
// DOES WORK
alert();
alert(jQuery(this).val()); // alerts e.g. "tube"

// DOESN'T WORK
alert(jQuery(this).val()); // alerts ""

我认为这可能是一个计时问题,但尝试使用setTimeout延迟我的单一警报调用没有帮助。

先谢谢你们,我希望我只是失明,并没有在IE8中找到另一个丑陋的行为。

3 个答案:

答案 0 :(得分:0)

我会在回调中使用最新的jQuery和on()以及:checked选择器:

jQuery(document).ready(function() {
    jQuery('input[type="radio"]').on(function('change blur mousedown click') {
         alert(jQuery('input[type="radio"]:checked').val());
    });
});

实际上这有点棘手,您无法在回调中使用“this”获取所选单选按钮,您必须使用其他选择器: How can I know which radio button is selected via jQuery?

答案 1 :(得分:0)

感谢您的回答,但没有成功。我不确定这是否是jQuery中的错误,或者只是我在特定情况下遇到的问题。似乎jQuery迫使IE8在字段真正改变之前触发更改事件。

我终于通过绑定到模糊事件并将其与powtacs结合来解决它:检查过这样的解决方案:

<script type="text/javascript">
jQuery(document).ready(function() {

   jQuery('input[type="radio"]').unbind('click.preset')
   .bind('click.preset', function() {
       jQuery(this).blur();
   }

   jQuery('input[type="radio"]').unbind('blur.preset')
   .bind('blur.preset', function() {
        doingStuffWith(jQuery('input[type="radio"]:checked').val());
    });
});
</script>

答案 2 :(得分:0)

IE8的公平选项是在每个无线电选项中创建一个类(!),并使用它来选择已选中的选项。在语义上它有点奇怪,但它对我来说很完美:

HTML

<input type="radio" name="example" class="example_class" value="1"/>#1
<input type="radio" name="example" class="example_class" value="2"/>#2
<input type="radio" name="example" class="example_class" value="3"/>#3

JS

var exampleValue = $('.example_class:checked').val();