2013-03-15 53 views
0

我试图重现Symfony的2食谱教程Add a new Tag嵌入形式的集合:添加标签的jQuery

我使用完全相同的代码,就像在教程,但我有一些问题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>

下一步: 地方添加一个脚本标记,在网页上所以你可以开始写一些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); 
} 

最后我写了在列表后面添加一个标签。

但是,当我点击添加标签链接时,不会出现新的标签输入字段。

+0

如果你的意思是当你点击添加标签链接,你添加到你的列表后,这是正常的。点击事件正在聆听你的'$ addTagLink'对象,所以只有当你点击列表中的添加标记链接时才会起作用。 – Snroki 2013-03-15 14:30:28

+0

我让你成为一个小提琴的例子:http://jsfiddle.net/GXy6g/ – Snroki 2013-03-15 14:47:00

+0

嘿非常感谢Coussinsky,但是Symfony如何使用$ addTagLink变量以及如何使用这个变量? – ChrisS 2013-03-15 14:58:54

回答

0

请参阅浏览器调试器。有没有错误? 也许你使用旧的jQuery版本? 确保jquery已启用并支持'on'事件(自1.9版本以来)。