我如何将ONCHANGE事件绑定到动态创建的选择菜单

问题描述 投票:-1回答:1

我在设置带有ajax的下拉菜单设置onchange事件时遇到问题。我知道我可能正在尝试将处理程序绑定到错误的位置,但是我到处都尝试无济于事!

最感谢您的帮助!

在最后一个#picksize函数之前,所有脚本都可正常运行-当我选择一个已创建的选项时,它不会运行#picksize函数

<script type="text/javascript">
$(document).ready(function () {
$("#topopt").change(function () {
var topopt_id = $(this).val();
var prodsize = <?php echo $prodsize ?>;
if(topopt_id != "") {
$.ajax({
url:"getoptions.php", 
data:{topopt:topopt_id},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#pickoption").html(resp);
}
});
$.ajax({
url:"getsizes.php", //gets options for picksize select
data:{topopt:topopt_id,prodsize:prodsize},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#picksize").html(resp);
}
});
$.ajax({
url:"session.php",
data:{topopt:topopt_id},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#pickall").html(resp);
}
});
$.ajax({
url:"getprices.php",
data:{topopt:topopt_id},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#priceblock").html(resp);
}
});
} else {}
});

$("#picksize").on('change','select',function () {
var picksize_id = $(this).val();
if(picksize_id != "") {
$.ajax({
url:"session.php",
data:{picksize:picksize_id},
type:'POST',
success:function(response) {
var resp = $.trim(response);
$("#pickall").html(resp);
}
});
} else {}
});

});
</script>

...


<div id="sizeblock">
<div class="select">
<select name="picksize" id="picksize" title="Pick a Size" onchange="">
<option value="">Choose a Print Type to see Sizes</option>
</select>
  </div>
</div>
javascript php ajax select dropdown
1个回答
0
投票

绑定动态创建的元素的最简单方法是使用"event delegation",它依赖于事件在DOM中冒泡的事实。不必担心绑定新元素本身,只需将change事件处理程序绑定到将一直存在的新元素的某些祖先即可。然后,当事件到达该祖先时,您可以检查事件对象本身,以确定事件起源于哪个元素,然后采取相应措施。

这是一个简化的示例,您可以轻松地适应您的用例:

// Bind the event handler to a static ancestor
document.querySelector(".container").addEventListener("change", function(event){
  // Check to see if the event originated from the dynamically created element.
  // event.target will reference the element, but you can use any criteria you
  // need to in order to determine if it is the right element.
  if(event.target.classList.contains("dynamic")){
    console.log("Dynamically added text box changed!");
  }
});

// Create some new content. Notice that no event 
// binding is added here.
let txt = document.createElement("input");
txt.classList.add("dynamic");
let ta = document.createElement("textarea");


// Inject the new content
document.querySelector(".container-content").append(txt);
document.querySelector(".container-content").append(ta);
<p>Add some content to each field and tab out to invoke the change event.<br>
The textbox will trigger the handler, but the textarea won't.</p>
<div class="container">
  <div class="container-content"><div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.