0

Symfony 2 クックブック チュートリアルを再現しようとしています 新しいタグを追加

チュートリアルとまったく同じコードを使用していますが、jQuery インクルードに問題があります。

new.html.twig :

<form action="..." method="POST" {{ form_enctype(form) }}>
    {# render the task's only field: description #}
    {{ form_row(form.description) }}

    <h3>Tags</h3>
    <ul class="tags" data-prototype="{{ form_widget(form.tags.vars.prototype)|e }}">
        {# iterate over each existing tag and render its only field: name #}
        {% for tag in form.tags %}
            <li>{{ form_row(tag.name) }}</li>
        {% endfor %}
    </ul>
    <a href="#" class="add_tag_link">Add a tag</a>
    {{ form_rest(form) }}
    {# ... #}
</form>

これは、base.html.twig に jquery を含める方法です。 <script src="http://code.jquery.com/jquery.js"></script>

次のステップ: ページのどこかに script タグを追加して、JavaScript の記述を開始できるようにします。

これを base.html.twig にもコピペしました。

// Get the ul that holds the collection of tags
var collectionHolder = $('ul.tags');

// setup an "add a tag" link
var $addTagLink = $('<a href="#" class="add_tag_link">Add a tag</a>');
var $newLinkLi = $('<li></li>').append($addTagLink);

jQuery(document).ready(function () {
    // add the "add a tag" anchor and li to the tags ul
    collectionHolder.append($newLinkLi);

    // count the current form inputs we have (e.g. 2), use that as the new
    // index when inserting a new item (e.g. 2)
    collectionHolder.data('index', collectionHolder.find(':input').length);

    $addTagLink.on('click', function (e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();

        // add a new tag form (see next code block)
        addTagForm(collectionHolder, $newLinkLi);
    });
});

function addTagForm(collectionHolder, $newLinkLi) {
    // Get the data-prototype explained earlier
    var prototype = collectionHolder.data('prototype');

    // get the new index
    var index = collectionHolder.data('index');

    // Replace '__name__' in the prototype's HTML to
    // instead be a number based on how many items we have
    var newForm = prototype.replace(/__name__/g, index);

    // increase the index with one for the next item
    collectionHolder.data('index', index + 1);

    // Display the form in the page in an li, before the "Add a tag" link li
    var $newFormLi = $('<li></li>').append(newForm);
    $newLinkLi.before($newFormLi);
}

最後に書きました リストの後にタグを追加します。

しかし、[タグの追加] リンクをクリックしても、新しいタグ入力フィールドが表示されません。

4

1 に答える 1

0

ブラウザー デバッガーを参照してください。エラーはありますか?古いバージョンの jquery を使っているのではないでしょうか? jquery が有効になっていて、'on' イベントがサポートされていることを確認してください (1.9 バージョン以降)。

于 2013-04-12T15:26:20.640 に答える