草庐IT

javascript - 根据先前的下拉选择更新下拉列表

coder 2025-03-12 原文

我有一个电子商务网站,其产品具有多种属性(例如尺寸、颜色等)

在每个产品页面上,每个属性都有一个下拉列表,其类别为 'attribute_price'

我还使用类 'hidden_​​attribute_value' 将每个产品的定价从我的数据库预加载到页面上。

因此,并非所有尺寸和颜色的组合都是一种选择。例如,我们可能有 'small_red''medium_red' 但没有 'large_red'

因此,如果他们从尺寸下拉菜单中选择 'large',则 'red' 不应作为颜色选项。

我目前拥有的是:

$("select.attribute_price").on("change", function(){

    var id = event.target.id;
    // determine which dropdown was changed (size or colour)
    var attribute_value = document.getElementById(id).value+'_';
    // get the value of the dropdown that they selected

    var other_attribute_ids = []
    var i;
    var other_attributes = document.getElementsByClassName("attribute_price");
    for(i=0; i<other_attributes.length; i++){
        if(other_attributes[i].id != id){
            var other_attribute_id = document.getElementById(other_attributes[i].id).id;
            other_attribute_ids.push(other_attribute_id);
        }
    }
    // create an array of all of the other dropdown ids excluding the one they changed

    var all_attribute_ids = []
    var i;
    var all_attributes = document.getElementsByClassName("hidden_attribute_value");
    for(i=0; i<all_attributes.length; i++){
        all_attribute_ids.push(all_attributes[i].id);
    }
    // create an array of all of the possible values that it can be

});

所以我有一个变量 'attribute_value',它类似于 'red_' 或 'blue_'。

我有一个名为 'all_attribute_values' 的数组,其中包含所有可能组合的隐藏输入的 ID。这些将具有诸如“small_red_”或“small_blue”之类的值。

我有一个名为 'other_attribute_ids' 的数组,其中包含尚未选择的其他下拉菜单的 ID。

因此,如果 'all_attribute_values' 中的项目不包含 'attribute_value',请从 'other_attribute_ids' 中删除该选项。

最佳答案

我已经根据您的用例创建了一个示例 html。解决方案也是如此,但是您应该从解决您的问题中获得灵感。

我考虑了独立的属性,因此解决方案将扩展到具有不同值的新属性。我还考虑过服务器响应是不可编辑的。

我在 jsfiddle 中有一个快速链接来检查解决方案

https://jsfiddle.net/nfLx6aok/1/

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<select id="size" class="attribute_price">
  <option value="small">Small</option>
  <option value="large">Large</option>
</select>

<select id="color" class="attribute_price">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="black">Black</option>
</select>

<select id="pattern" class="attribute_price">
  <option value="solids">Solids</option>
  <option value="checked">Checked</option>
  <option value="dots">Dots</option>

</select>

<input type="hidden" id="small_red_solids" class="hidden_attribute_value">
<input type="hidden" id="small_black_dots" class="hidden_attribute_value">
<input type="hidden" id="large_green_checked" class="hidden_attribute_value">

<script>

  // on page load 
  $( document ).ready(function() {
    renderOptions();
});


  $("select.attribute_price").on("change", function () {
    renderOptions();
  });

  function renderOptions() {
    // create an array of all of the possible values that it can be
    // allowed_attribute_values = ['small_red', 'large_blue']
    var allowed_attribute_values = [];
    var all_attributes = document.getElementsByClassName("hidden_attribute_value");
    for (var i = 0; i < all_attributes.length; i++) {
      allowed_attribute_values.push(all_attributes[i].id);
    }

    function getAllPossibleValues(current_level, all_attributes) {
      var depth_index = all_attributes.length;
      var selected_combination = '';
      for (var i = 0; i < depth_index; i++) {
        if (i <= current_level) {
          selected_combination += all_attributes[i].value;
          if (i != all_attributes.length - 1) {
            selected_combination += '_';
          }
        }
      }

      // hide all lower options
      for (var i = current_level + 1; i < depth_index; i++) {
        var selectedIdOptions = all_attributes[i].options;
        all_attributes[i].value = null
        for (var j = 0; j < selectedIdOptions.length; j++) {
          // hide all lower options
          selectedIdOptions[j].hidden = true;
          var el = allowed_attribute_values.find(a => a.includes(selected_combination + selectedIdOptions[j].value));
          if (el) {
            selectedIdOptions[j].hidden = false;
          }
        }
      }
    }

    if (event) {
      var id = event.target.id;
    } else {
      var id = document.getElementsByClassName("attribute_price")[0].id;
    }

    var other_attributes = document.getElementsByClassName("attribute_price");
    for (var i = 0; i < other_attributes.length; i++) {
      if (other_attributes[i].id == id) {
        allPossibleValues = getAllPossibleValues(i, other_attributes);
        // we dont want to go deeper as of now
        break;
      }
    }
  }
</script>

关于javascript - 根据先前的下拉选择更新下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52595129/

有关javascript - 根据先前的下拉选择更新下拉列表的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby - RVM 使用列表[0] - 2

    是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论

  3. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  4. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  5. ruby - Rails 3 的 RGB 颜色选择器 - 2

    状态:我正在构建一个应用程序,其中需要一个可供用户选择颜色的字段,该字段将包含RGB颜色代码字符串。我已经测试了一个看起来很漂亮但效果不佳的。它是“挑剔的颜色”,并托管在此存储库中:https://github.com/Astorsoft/picky-color.在这里我打开一个关于它的一些问题的问题。问题:请建议我在Rails3应用程序中使用一些颜色选择器。 最佳答案 也许页面上的列表jQueryUIDevelopment:ColorPicker为您提供开箱即用的产品。原因是jQuery现在包含在Rails3应用程序中,因此使用基

  6. objective-c - 在设置 Cocoa Pods 和安装 Ruby 更新时出错 - 2

    我正在尝试为我的iOS应用程序设置cocoapods但是当我执行命令时:sudogemupdate--system我收到错误消息:当前已安装最新版本。中止。当我进入cocoapods的下一步时:sudogeminstallcocoapods我在MacOS10.8.5上遇到错误:ERROR:Errorinstallingcocoapods:cocoapods-trunkrequiresRubyversion>=2.0.0.我在MacOS10.9.4上尝试了同样的操作,但出现错误:ERROR:Couldnotfindavalidgem'cocoapods'(>=0),hereiswhy:U

  7. ruby - 如何使用 Selenium Webdriver 根据 div 的内容执行操作? - 2

    我有一个使用SeleniumWebdriver和Nokogiri的Ruby应用程序。我想选择一个类,然后对于那个类对应的每个div,我想根据div的内容执行一个Action。例如,我正在解析以下页面:https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=puppies这是一个搜索结果页面,我正在寻找描述中包含“Adoption”一词的第一个结果。因此机器人应该寻找带有className:"result"的div,对于每个检查它的.descriptiondiv是否包含单词“adoption

  8. ruby - 如何根据长度将路径数组转换为嵌套数组或散列 - 2

    我需要根据字符串路径的长度将字符串路径数组转换为符号、哈希和数组的数组给定以下数组:array=["info","services","about/company","about/history/part1","about/history/part2"]我想生成以下输出,对不同级别进行分组,根据级别的结构混合使用符号和对象。产生以下输出:[:info,:services,about:[:company,history:[:part1,:part2]]]#altsyntax[:info,:services,{:about=>[:company,{:history=>[:part1,:pa

  9. ruby-on-rails - Rails Associations 的更新方法是什么? - 2

    这太简单了,太荒谬了,我在任何地方都找不到关于它的任何信息,包括API文档和Rails源代码:我有一个:belongs_to关联,我开始理解当您没有关联时您在Controller中调用的正常模型方法与您有关联时调用的方法略有不同。例如,我的关联在创建Controller操作时运行良好:@user=current_user@building=Building.new(params[:building])respond_todo|format|if@user.buildings.create(params[:building])#etcetera但我找不到关于更新如何工作的文档:@user

  10. ruby - 我正在学习编程并选择了 Ruby。我应该升级到 Ruby 1.9 吗? - 2

    我完全不是程序员,正在学习使用Ruby和Rails框架进行编程。我目前正在使用Ruby1.8.7和Rails3.0.3,但我想知道我是否应该升级到Ruby1.9,因为我真的没有任何升级的“遗留”成本。缺点是什么?我是否会遇到与普通gem的兼容性问题,或者甚至其他我不太了解甚至无法预料的问题? 最佳答案 你应该升级。不要坚持从1.8.7开始。如果您发现不支持1.9.2的gem,请避免使用它们(因为它们很可能不被维护)。如果您对gem是否兼容1.9.2有任何疑问,您可以在以下位置查看:http://www.railsplugins.or

随机推荐