2015-08-21 58 views
0

你好我試圖調用一個函數時,點擊一些元素。無法將jquery委託應用到dinamically生成的元素

我在做一個使用symfony php框架的表單。在此之後: http://symfony.com/doc/current/cookbook/form/form_collections.html#template-modifications

我readed這樣的: https://stackoverflow.com/a/1207393/4386551

不過,這並不與a.delete元素的工作,它爲a.add只。

var $collectionHolder; 

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

jQuery(document).ready(function() { 
    // Get the ul that holds the collection of tags 
    $collectionHolder = $('ul.details'); 

    // 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); 
    }); 
    $(".details").on("click", "a.add", function(){alert("HEY");}); 
    $(".details").on("click", "a.delete", function(){alert("HEY");}); 

}); 

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); 
    addTagFormDeleteLink($newFormLi); 

} 

function addTagFormDeleteLink($tagFormLi) { 
    var $removeFormA = $('<a href="#" class="delete">delete this tag</a>'); 
    $tagFormLi.append($removeFormA); 

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

     // remove the li for the tag form 
     $tagFormLi.remove(); 
     //reload_total(); 

    }); 
} 

a.delete和jquery.on有什麼問題?

回答

0

嘗試改變:

$(".details a.add").on("click", function(){alert("HEY");}); 
$(".details a.delete").on("click", function(){alert("HEY");}); 

或者這樣:

$(".details").on("click", "a.add, a.delete", function(){alert("HEY");}); 
+0

謝謝,但仍無法在a.delete工作。 – user92083452

相關問題