简体   繁体   English

使用AJAX后,我无法调用onclick javascript函数

[英]I can't call my onclick javascript function after using AJAX

I'm totally newbie in javascript/jQuery and i have a little problem :) 我是javascript / jQuery的新手,我有一个小问题:)

I'm using AJAX to get datas to generate and populate form fields. 我正在使用AJAX来获取数据以生成和填充表单字段。 After that, i would like to add and/or remove fields with javascript functions but it doesn't work. 在那之后,我想使用javascript函数添加和/或删除字段,但是它不起作用。

As i'm learning, i make my code step by step, so the following code implement the ajax request (which is working perfectly), and the function which i would like to call with an on click attribute on an + image. 在我学习的过程中,我逐步编写了代码,因此以下代码实现了ajax请求(运行良好)以及要在+图像上带有on click属性调用的函数。

$(document).ready(function(){

var id = $('#subId').val();
var num     = $('.cloneSub').length;
var newNum  = new Number(num + 1);

$.ajax({
    type: 'POST',
    dataType: 'json',
    url: '/admin/popsub2/',
    data: 'id='+id,
    async: false,
    success: function(data){

        $.each(data, function(key, val){

            // Add and populate the input text element
            var newElem = $('#sub' + num).clone().attr('id', 'sub' + newNum);
            newElem.children(':first').attr('id', 'sub' + newNum).attr('name', 'sub' + newNum);

            $('#sub' + num).attr('value', val);

            $('#sub' + num).after(newElem);
            $(newElem).before('<br />');

            // Simply add the select element
            var newSelect = $('#editMenu_article' + num).clone().attr('id', 'editMenu_article' + newNum);
            newSelect.children(':first').attr('id', 'editMenu_article' + newNum).attr('name', 'editMenu_article' + newNum);

            $('#editMenu_article' + num).after(newSelect);
            $(newSelect).before('<br />');
        });
    },

    failure: function(){
        alert('echec !!!');
    }
});


function addField(){

    // Add the input text element
    var newElem = $('#sub' + num).clone().attr('id', 'sub' + newNum);
    newElem.children(':first').attr('id', 'sub' + newNum).attr('name', 'sub' + newNum);

    $('#sub' + num).attr('value', val);

    $('#sub' + num).after(newElem);
    $(newElem).before('<br />');

    // Add the select element
    var newSelect = $('#addMenu_article' + num).clone().attr('id', 'addMenu_article' + newNum);
    newSelect.children(':first').attr('id', 'addMenu_article' + newNum).attr('name', 'addMenu_article' + newNum);

    $('#addMenu_article' + num).after(newSelect);
    $(newSelect).before('<br />');

}

});

The addField() function doesn't work at all, and i don't know why. addField()函数根本不起作用,我也不知道为什么。 AJAX seems to keep a hand on the script execution. AJAX似乎可以帮助脚本执行。

Thanx for your help. 感谢您的帮助。

UPDATE UPDATE

My + image is : 我的+图片是:

<img src="images/plus.png" id="editSub2" />

Following your help i tried those codes : 在您的帮助下,我尝试了以下代码:

$('#editSub2').live('click', function(){ ... });

$('#editSub2').bind('click', function(){ ... });

But nothing works. 但是没有任何效果。

You've declared addField() inside the scope of your jQuery document ready callback. 您已经在jQuery文档就绪回调的范围内声明了addField() No one outside that function will be able to know about it. 该功能之外的任何人都无法了解它。 You can declare it as a global function, but you'll be better encapsulating it. 您可以将其声明为全局函数,但是最好封装它。 You might find something like Javascript Patterns a helpful resource. 您可能会发现像Javascript Patterns这样的有用资源。

If the image is created dynamically, you should bind the click event after creating it, if not, on the document ready block, you must bind it. 如果图像是动态创建的,则应在创建click事件后将其绑定,否则,必须在文档就绪块上将其绑定。

$('img#myimg').bind("click", function(){

// Add the input text element
    var newElem = $('#sub' + num).clone().attr('id', 'sub' + newNum);
    newElem.children(':first').attr('id', 'sub' + newNum).attr('name', 'sub' + newNum);

    $('#sub' + num).attr('value', val);

    $('#sub' + num).after(newElem);
    $(newElem).before('<br />');

    // Add the select element
    var newSelect = $('#addMenu_article' + num).clone().attr('id', 'addMenu_article' + newNum);
    newSelect.children(':first').attr('id', 'addMenu_article' + newNum).attr('name', 'addMenu_article' + newNum);

    $('#addMenu_article' + num).after(newSelect);
    $(newSelect).before('<br />');


});

Sounds like you've run into the DOM event handler trap. 听起来您好像遇到了DOM事件处理程序陷阱。 This issue makes more sense if you've ever handled events sans jQuery. 如果您曾经处理过没有jQuery的事件,则此问题更有意义。

Basically, what happens when you do this: 基本上,执行此操作会发生什么:

$(".images").click(myFunc);

is that jQuery goes and finds all elements that match the selector and binds the function myFunc to the onclick event, using this (roughly) code: jQuery会使用以下(大致)代码查找与选择器匹配的所有元素,并将函数myFunc绑定到onclick事件:

element.onclick = myFunc;

(It actually does something more complicated, but just assume that thats what it does) (它实际上做的事情更复杂,但是假设那就是它所做的事情)

and that happens when you run the above code and only then, any extra elements added to the DOM don't have that event added, jQuery was never told to add them! 而且,当您运行上述代码时就会发生这种情况,只有到那时,添加到DOM的任何其他元素都不会添加该事件,jQuery从未被告知要添加它们!

However, all is not lost, you can use the brilliant .live() function in jQuery to bind to all matching elements, existing and future. 但是,一切都不会丢失,您可以在jQuery中使用出色的.live()函数绑定到所有匹配的元素(现有元素和将来元素)。 Its simpler and easier to use than having to manually rebind new elements and less error prone. 与手动重新绑定新元素相比,它更简单,更易于使用,并且出错率更低。 One minor downside is that it interferes with event ordering, and you have to use a .bind() -like interface, so you use .live("click", myfunc) instead. 一个较小的缺点是,它会干扰事件排序,因此您必须使用类似.bind()的接口,因此请改用.live("click", myfunc)

EDIT 编辑

In light of reading more of your question, it seems that the problem is that you have is that you have bound to #editSub2 but are generating #editSub<n> so jQuery has no idea what you are on about. 鉴于阅读了更多的问题,看来问题在于您已经绑定到#editSub2但正在生成#editSub<n>因此jQuery不知道您要做什么。 I suggest using classes to push common functionality onto elements, and IDs for unique elements, for one its probably more efficient. 我建议使用类将通用功能推送到元素上,并将ID推送到唯一元素上,因为它可能更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM