gpt4 book ai didi

javascript - JQuery 选择器在动态创建的内容中不起作用?

转载 作者:行者123 更新时间:2023-11-30 21:17:05 24 4
gpt4 key购买 nike

我正在尝试检索 .html() .val() 或 html 元素中的其他内容,这是我的 html 代码(动态生成):

<div class="presupuesto"><h2 class="precio" id="precio" value="1202">1.202,00 €</h2>

I need the .val() attribute!

我想用 JQuery 和 JavaScript 显示,从选择中选择了什么选项,然后显示有关 h2 标签(价格)的信息。这是我的 JS 代码:

$('select').on('change', function (e) {

var optionSelected = $("option:selected", this);
var valueSelected = this.value;
alert(valueSelected);
alert(("#precio").val());

});

The first alert(valueSelected) works well, but the second one triggers a TypeError

提前致谢!

最佳答案

正如您所说,您拥有动态生成的元素。然后你需要使用 event-delegation :-

$(document).on('change','select',function(){
alert($(this).val()); // to get select value
alert($('#precio').attr('value')); // try to use data-attribute which is standered way
});

注意:-<h1>,<h2>..,<div>,<ul><li><p>....这些元素没有 value属性(以标准方式)。所以使用 data-attribute他们的选项如下所示:-

<h2 class="precio" id="precio" data-value="1202">1.202,00 €</h2>

然后像下面这样更改 jQuery 代码:-

 alert($('#precio').data('value'));

关于javascript - JQuery 选择器在动态创建的内容中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45563474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com