0

このフィドルを機能させるにはどうすればよいですか: http://jsfiddle.net/gAHwW/

function $escape(string) { 
    return string.replace(/\\(\[|\]\\)/g,'\\\\$1');
}

$(function() {
    $('input[type="button"]').click(function() {
        alert($escape( $(this).attr('id') )); // to show you what the escape does

        $('#' + $(this).attr('id')).hide(); // doesn't work
        $('#' + $escape( $(this).attr('id') )).hide(); // doesn't work
        $('#alsosquare[]').hide(); // doesn't work

        //$(this).hide(); // works
        //$('#alsosquare\\[\\]').hide(); // works
    });
});​

名前/ID で要素を動的に選択する必要があり、それらの名前/ID には角かっこを含めることができます。

ありがとう!

4

1 に答える 1

3

\\角かっこを二重にescape( )する必要があります。

これがデモです:http://jsfiddle.net/k3YyX/


これがjQueryドキュメントからの引用です:

メタ文字(! "#$%&'()* +、。/ :; <=>?@ [\] ^` {|}〜など)のいずれかをリテラル部分として使用する場合名前の場合は、2つの円記号で文字をエスケープする必要があります:\\。たとえば、id = "foo.bar"の要素がある場合は、セレクター$( "#foo \\。bar")を使用できます。


アップデート:

これが動作状態のフィドルです:http://jsfiddle.net/gAHwW/1/

私がしたのはあなたの関数'\\\\$1'でこれに置き換えることだけでした。'\\$1'$escape

于 2012-05-22T03:39:36.560 に答える