jQuery在动态创建的div中选择动态类ID [英] jquery selecting dynamic class id inside dynamically created div

查看:145
本文介绍了jQuery在动态创建的div中选择动态类ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些JS,可以动态创建一个新的div(表单内的输入).效果很好.我另外有一些jquery检查下拉输入,如果单击特定选择,则会显示一个单独的div.效果很好.

I have some JS that dynamically creates a new div (inputs inside of a form). It works great. I separately have some jquery that checks a dropdown input, and shows a separate div if a specific selection is clicked. It works great.

如果我尝试使用jquery在其中一个动态创建的div中显示一个单独的div,它将无法正常工作.它的第一个实例确实起作用,但是没有一个动态创建的实例.在四处搜寻之后,似乎我需要一个代表团,但对于我的具体情况,我似乎无法弄清楚.

If I try to use the jquery to show a separate div inside one of the dynamically created ones, it does not work. The first instance of it does work, but none of the dynamically created ones. After searching around, it looks like I need a delegation, but I can't seem to figure it out for my specific situation.

JSFiddle: http://jsfiddle.net/Xyzeg/(在第一个字段,以便事件结束).小提琴包含用于动态创建div的其他JS.

The JSFiddle: http://jsfiddle.net/Xyzeg/ (change the "CPI" dropdown in the first field, for the event to go off). The fiddle includes the other JS for dynamically creating the divs.

任何指针将不胜感激.

<div style="float:left">
<div id='dynamicInput'>Pension 1: Amount: $<input type='text' name='adjustmentInputs[]' value='0' size='13' maxlength='20'>Start Year:
<input type='text' name='adjustmentInputs[]' value='2032' size='5' maxlength='6'>
<input type='hidden' name='adjustmentInputs[]' value='2100'>
<select name='adjustmentInputs[]'>
  <option value='InflationAdjusted'>Inflation Adjusted</option>
  <option value='NotInflationAdjusted'>Not Inflation Adjusted</option>
</select>by
<select name='adjustmentInputs[]' class='pensionAdjustment1'>
  <option value='CPI'>CPI</option>
  <option value='constantPercentage'>Constant %</option>
</select>
<div id='constantPercentageText1' style='display: none'>@ <input type='text' name='adjustmentInputs[]' value='3' size='5' maxlength='6'>%</div>
</div>
   <input type="button" value="Add another Portfolio Adjustment" onClick="addInput('dynamicInput');">
</div>
<script>
$("[class*=pensionAdjustment]").change(function() {
    var n = $(this).attr('class').replace('pensionAdjustment', '');
    var newId = "constantPercentageText" + n;
    var selectedItem = $(this).children('option:selected');
    if ($(this).val() == 'constantPercentage') {
        $("#constantPercentageText" + n).css('display', 'inline');
        $("#constantPercentageText" + n).show();
    } else {
        $("#constantPercentageText" + n).css('display', 'none');
    }
});  
</script>

推荐答案

您需要委派新创建的元素!

You need to delegate with newly created elements!

更改此行

$("[class*=pensionAdjustment]").change(function() {

$(document).on('change',"[class*=pensionAdjustment]",  function() {

这篇关于jQuery在动态创建的div中选择动态类ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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