Ajax请求返回与选择列表id="country"
如何获取动态创建的HTML元素的值?
HTML代码氩主JS文件有事件单击我在尝试获得创建选择列表值我DINAMIC并得到警报:未定义
var country = $('#country option:selected').val();
如何可以获得价值吗?
Ajax请求返回与选择列表id="country"
如何获取动态创建的HTML元素的值?
HTML代码氩主JS文件有事件单击我在尝试获得创建选择列表值我DINAMIC并得到警报:未定义
var country = $('#country option:selected').val();
如何可以获得价值吗?
如果事件在AJAX结束之前被绑定,那么$('#country option:selected')
将找不到该元素,因为在绑定元素时该元素尚不存在。如果你看它的body
标签中虽然使用.find
应该解决您的问题:
$('body').find('#country').find('option:selected').val()
此外,使用#country option:selected
将导致浏览器首先寻找所有选定的选项,然后内#country
寻找那个。所以使用(#country).find('option:selected')
通常会更快,因为它首先找到#country
。
希望这是你正在寻找的答案。
假设你不加入这个“选择”列表中的网页,这样做:
... // inside the event click handler, do this:
$.ajax("[*some url goes here*]")
.done(function(response){ // response will look like "<select id='country'> ... </select>"
// Dynamically create a select element in memory
var select = $(response);
// Find the selected option in the select
var chosenOption = $(select).find('option:selected');
var value = null;
// Null check, incase no option was checked and the chosenOption variable is null
if (chosenOption != null) {
value = $(chosenOption).val();
}
});
...
*动态。您必须向我们展示HTML及其构建方式 - 我们无法神奇地知道您的后端工作 –
我认为您不会将返回的HTML添加到DOM。你必须做这样的事情:'$(“#placeholder”)。html(htmlResult);''占位符'是你的页面中已经存在的元素。 – Mahmoodvcs
您可以尝试使用自动递增的数字设置创建的项目的id属性。 –