创建的新元素,在ready文档之后调用jquery方法不起作用

我有以下代码

$(document).ready(function() { // When change the value in select it will send id to controller in order to return the price of service. $(".select-service").change(function(){ var element_id = $(this).attr('id'); $.post("/services/get_price_of", { message: this.value }, function(data){ $("#" + element_id).parent().find(".price-input").val(data); }) }); }); 

该页面加载了一个选择,但我可以动态添加更多选择。 问题是,对于动态添加的所有选择,事件早期不起作用。 有人能帮我吗?

问候。

PD:抱歉我的英语不好。

使用jquery

http://api.jquery.com/on/

 $(document).ready(function() { $("select").on("change", ".select-service", function(event){ var element_id = $(this).attr('id'); $.post("/services/get_price_of", { message: this.value }, function(data){ $("#" + element_id).parent().find(".price-input").val(data); }) }); }); 

从jQuery 1.7开始,不推荐使用.live()方法

您可以使用on()及其selector参数来使用事件委派。 例如,要捕获#container p元素的所有点击(甚至在附加事件侦听器后添加的p元素),您可以使用以下代码:

 $("#container").on('click', 'p', function() { $(this).css('color', 'red'); }); 

此外,尽管与您的问题无关,但在回调中使用事件目标的更优雅方法是:

 var self = $(this); someFunction(function() { self.css('color', 'red'); });