【问题标题】:Brackets in jQuery selectorsjQuery 选择器中的括号
【发布时间】:2014-10-08 16:41:19
【问题描述】:

我的 jquery 遇到了一些问题,我真的无法让它工作。

我正在进行一项调查,每个问题的最后一个单选选项都是其他选项,因此用户可以输入自定义文本(如果喜欢)。 我希望隐藏文本框,直到或如果选中了收音机并且文本框应该是对等的。

我试过这个:

    $(document).ready(function () {
    $("#custom_form_custom_field_2_block").hide();

    $("input:radio[name=custom_form[custom_field_1]]").change(function () {
        if (this.value == "jeg har et helt 4. forslag") {
            $("#custom_form_custom_field_2_block").fadeIn();
        } else {
            $("#custom_form_custom_field_2_block").fadeOut();
        }

    });

    $("#custom_form_custom_field_2_block").focusout(function () {
        $("input:radio[name=Title]:checked").attr('value', $("#custom_form_custom_field_2_block").val());
    });
});

我在这里有一个 mt fiddle 的链接:JSFiddle

希望你能帮忙, 问候 托马斯

【问题讨论】:

  • 你必须在你的 jsFiddle 中启用 jQuery。使用左侧的菜单栏选择正确的版本。然后在 Chrome/IE 中运行开发工具栏或在 Firefox 中运行 Firebug。错误是Uncaught Error: Syntax error, unrecognized expression: input:radio[name=custom_form[custom_field_1]]

标签: javascript jquery textbox radio-button show-hide


【解决方案1】:

我相信这条线是问题所在:

$("input:radio[name=custom_form[custom_field_1]]")

方括号(“[”和“]”)是 css 选择器中的保留字符(您将这样的选择器传递给 jQuery 的 $() 函数),并且您使用方括号作为元素名称的一部分。试试这个:

$("input:radio[name=custom_form\\[custom_field_1\\]]")

这会产生一个

的 css 选择器
input:radio[name=custom_form\[custom_field_1\]]

从而转义括号。可能不适用于所有浏览器。

编辑:这里有一些关于在 css 选择器中转义字符的附加信息: http://mathiasbynens.be/notes/css-escapes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-22
    • 2015-12-11
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 2013-02-03
    • 1970-01-01
    相关资源
    最近更新 更多