【问题标题】:Clear Select options when selecting one field while using multiple forms on same page在同一页面上使用多个表单时选择一个字段时清除选择选项
【发布时间】:2010-03-22 11:13:16
【问题描述】:

我有一种情况,第二个选择列表选项是从第一个选择列表选择选项生成的。就像当我们选择 Country 时,在下一个选择列表中会生成相应的状态。

就我而言,我在单个页面上有多个相同的表单。谁能告诉我如何在多个表单上实现它。

我尝试了以下代码,但没有成功

        $(".country").change(function(){
       $.get("sample.php?val=" + $(this).val(),
        function(data){
            $(this).parent().next().children('.state').children('option').remove();
            $(this).parent().next().children('.state').append(data);
        });

在此先感谢您的支持

【问题讨论】:

  • 您能否发布 HTML(以告知列表在哪里)以及来自 sample.php 的示例响应?
  • 感谢大家的支持

标签: jquery forms select


【解决方案1】:

假设“多种形式”都在同一个 <form> 元素中包含 <select class='country'><select class='state'>,您可以使用 .closest().find() 进行遍历,而不是与精确的 DOM 定位绑定:

$('.country').change(function() { 
  var $stateSelect = $(this).closest('form').find('select.state');

  $.get('sample.php?val='+$(this).val(), function(data) {
    $stateSelect.empty().append(data);
  });
});

此外,您在回调中使用的 $(this) 可能无法正常工作。该回调函数使用 this 作为 jQuery 的 AJAX 选项对象调用。如果您需要保留它以便在事件函数内部的其他回调/闭包中使用,您可以使用函数范围将var $this = $(this); 保存在事件函数中(就像我保存了$stateSelect)。

【讨论】:

    【解决方案2】:
        $(".country").change(function(){
       $.get("sample.php?val=" + $(this).val(),
        function(data){
            // console.log($this);
            $(this).parent().next().children('.state').children('option').remove();
            $(this).parent().next().children('.state').append(data);
        });
    

    我不能 100% 确定,但您可能会误解 function(data) 中的 this。尝试在我注释掉的行中运行console.log($this);

    以下是否有效? this 在 JavaScript 中是一个讨厌的概念,但它功能强大,值得学习。

        $(".country").change(function(){
         var country = $(this);
       $.get("sample.php?val=" + $(this).val(),
        function(data){
            country.parent().next().children('.state').children('option').remove();
            country.parent().next().children('.state').append(data);
        });
    

    【讨论】:

      【解决方案3】:

      假设你的元素之间的关系是正确的,这应该可以工作,更简洁一点:

      $('.country').change(function() { 
        var sel = $(this).parent().next().children('.state');
        $.get('sample.php?val='+$(this).val(), function(data) {
          sel.html(data);
        });
      });
      

      问题是this 没有引用您认为$.get 返回时所做的事情,因为它是异步的,需要存储该引用并在返回时使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-10
        • 2015-12-22
        • 2023-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-18
        • 1970-01-01
        相关资源
        最近更新 更多