【问题标题】:JQuery narrow selection in dynamically created elementsJQuery 在动态创建的元素中缩小选择范围
【发布时间】:2012-02-23 14:48:41
【问题描述】:

我有一些使用 perl 动态生成的 Select/Option html 代码。我使用 JQuery 在下面的 div 中显示每个选项的值。我的问题是如何将 JQuery 选择范围缩小到每个选择标签?我现在拥有它的方式是选择所有标签。

function changeDesc() {

  var selectionValue = $('.RandomDiv > fieldset > legend > select').val();
  $('.RandomDiv > fieldset > div').html(selectionValue);
}

$('.RandomDiv > fieldset > legend > select').each(function () {
$(this).change(changeDesc); });

我不能真正在所有标签上加上一个 id,因为它们是动态生成的,而且可能有很多。 我是 JQuery 的新手,我确信我正在寻找的答案可能并不难,但我似乎无法得到它。谢谢

【问题讨论】:

  • HTML 将帮助我们更好地帮助您。
  • 您能澄清一下您要完成的工作吗?您是否尝试选择具有给定值的单个选择标签?

标签: jquery select dynamic selection option


【解决方案1】:

试试这个。

function changeDesc() {
   //Here this will point to the select element which triggered change event
   $('.RandomDiv > fieldset > div').html($(this).val());
}

$('.RandomDiv > fieldset > legend > select').change(changeDesc);

您可以使用这样的匿名函数,而不是使用单独的函数,也可以使用closest 方法查找封闭的fieldset 元素并找到它的子元素div

$('.RandomDiv > fieldset > legend > select').change(function() {
   //Here this will point to the select element which triggered change event
   var $this = $(this);
   $this.closest('fieldset').children('div').html($this.val());
});

【讨论】:

  • 您刚才描述的较短的随机函数非常完美。谢谢你。看着它是有道理的,但谁知道它会持续多久。
【解决方案2】:

这个:

function displayDesc() {
  var classSelectionValue;
  classSelectionValue = $('.ClassDescriptionDiv > fieldset > legend > select').val();
  $('.ClassDescriptionDiv > fieldset > div').html(classSelectionValue);
}

应该是:

function displayDesc() {
  var classSelectionValue = $(this).val();
  $(this).closest("fieldset").children("div").html(classSelectionValue);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    相关资源
    最近更新 更多