如何使用<a> that Was Created Appending Stuff

时间:2015-08-24 18:40:57

标签: javascript jquery forms submit

This is what I currently have:

var popupContent = ''
    function createMessage(msg,pl) {
        return [
            "<p>" + msg + "</p>",
            "<form action='" + pl + "' method='post' accept-charset='utf-8'>",
                "<ul class='cd-buttons no_margin'>",
                    "<li><a class='submit'>Yes</a></li>",
                    "<li><a class='popup-close'>No</a></li>",
                "</ul>",
            "</form>",
            "<a class='cd-popup-close popup-close img-replace'>Close</a>"
        ].join('');
    }

    //Accept Employement Request
    $('.popup1').on('click', function() {
        employeeName = $(this).siblings('.js-employee-name').text();
        var message = "Are you sure you want to hire <b>" + employeeName + "</b>?"
        var postLink = "/hire-employee"

        createMessage();

        $(".cd-popup-container").append( createMessage(message, postLink) );
    });

    $('.submit').click(function(){
        $('form').submit();
    });

But this doesn't seem to work.

So how can I submit this the form created by the createMessage function when the with that class submit is clicked?

Thank you very much. Let me know if I wasn;t clear enough.

1 个答案:

答案 0 :(得分:1)

我建议您使用<button>而不是锚点,并使用按钮的默认行为。

使用

<button class='submit'>Yes</button>

然而,解决您当前的问题。

目前您使用的是&#34; direct&#34;绑定,它只会附加到代码进行事件绑定调用时页面上存在的元素。

  

委托事件的优势在于它们可以处理来自稍后添加到文档的后代元素的事件。

正在动态创建元素。

您需要使用Event Delegation。您必须使用委托事件方法来使用.on()

一般语法

$(staticParentElement).on(event, selector, eventHandler); 

实施例

$(".cd-popup-container").on('click', '.submit', function(event){
    $('form').submit();
    event.preventDefault(); //Cancel default behaviour of anchor
});