JQuery函数仅适用于函数 [英] JQuery function only works within a function

查看:234
本文介绍了JQuery函数仅适用于函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有下拉列表的页面和ADD NEW中的一个选项。为它创建的函数效果很好。

I have a page with a dropdown list and one of the options in ADD NEW. The function created for it works great.

$('#town_id').on('change', function(){
    if($(this).val() == "ADD_NEW"){
        console.log('Add New');
        $('#town_id').val('');
        $('#town_id').trigger('chosen:updated');
        $('#modal-1').modal('show');
    }
});

问题是有时候选择框根本不在页面上,我会将其添加到页面中带有jquery的页面。这篇文章也有效,但是在运行上面的代码时,从jquery添加的ADD NEW没有被提取。如果我将上面的代码放在添加选择代码下面,然后在下拉列表中选择添加新功能就可以了。

The problem is that sometimes the selectbox will not be on the page at all and I will append it into the page with jquery. This piece works too but the ADD NEW that was added from the jquery doesn't get picked up when running the code above. If I place the code above under the adding select code and then select ADD NEW in the dropdown it works ok.

// remove towns text
$('.towns').html('<select class="form-control chosen add_town" name="town_id" id="town_id" data-rule-required="true" data-placeholder="Choose a town"></select');
$("#town_id").chosen({disable_search_threshold: 15});
$("#town_id").css('width', '100%');


// add chosen select
$('#town_id').append('<option value="' + result.id + '" selected>' + result.name + '</option>');
$('#town_id').append('<option value="ADD_NEW">Add new town...</option>');
$('#town_id').trigger('chosen:updated');

有没有办法让它工作而不重复选择代码?

Is there a way to make it work without duplicating the select code?

推荐答案

是的,有一个解决方案。您必须使用委托,因为HTML元素是动态创建的。

Yes there is a solution. You have to use delegation because the HTML element is created dynamically.

考虑 .towns 元素的容器选择框和 #town_id 选择框语法如下:

Considering the .towns element the container of the select box and #town_id the select box the syntax looks like this:

$('.towns').on('change', '#town_id', function(){
    if($(this).val() == "ADD_NEW"){
        console.log('Add New');
        $('#town_id').val('');
        $('#town_id').trigger('chosen:updated');
        $('#modal-1').modal('show');
    }
});

是的,这适用于静态和动态选择框。

And yes, this will work for both static and dynamic select box.


直接和委托事件



当<$ c时提供了$ c> selector ,事件处理程序称为委托。当事件直接发生在绑定元素上时,不会调用处理程序,而仅适用于与选择器匹配的后代(内部元素)。 [...]

Direct and delegated events

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. [...]

事件处理程序仅绑定到当前选定的元素; 在您的代码调用 .on() 时,页面上必须存在这些内容。

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

阅读更多内容

这篇关于JQuery函数仅适用于函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆