1

js.erbファイルに新しい要素を追加し、新しく追加された要素にクリックイベントを割り当てようとしています。

これは私がjs.erbに持っているものです:

$("#<%= linkid %>").on("click", '<%= j function(event) {$(this).parent().next().toggle(); event.preventDefault();}) %>' );

関数を記述している「$」を使用して構文エラーが発生します。ここでの修正は何ですか?この関数をこのファイル内の変数に入れる必要がある場合、どうすればよいですか?一般的に、より良い方法はありますか?

更新:エラーメッセージ

/create.js.erb:7: syntax error, unexpected $undefined
....append= ( j function(event) {$(this).parent().next().toggle...
...                               ^
/create.js.erb:7: syntax error, unexpected ')', expecting keyword_end
...(); event.preventDefault();}) );@output_buffer.safe_concat('...
...                               ^):
4

1 に答える 1

2

内部のもの<%= ... %>はJavaScriptではなくRuby式であると想定されています。これ:

<%= j function(event) {$(this).parent().next().toggle(); event.preventDefault();}) %>

ERBはまったく必要ありません。それは単なる古いJavaScriptです。また、jQueryの2番目の引数$(...).on('click', ...)は、JavaScript文字列ではなく、JavaScript関数である必要があります。あなたはこれを求めている:

$("#<%= linkid %>").on("click", function(event) {
    $(this).parent().next().toggle();
    event.preventDefault();
});
于 2012-10-13T19:40:49.057 に答える