【问题标题】:Javascript - Goto url based on dynamically populated drop downJavascript - 基于动态填充的下拉菜单转到 url
【发布时间】:2017-03-28 06:54:37
【问题描述】:

我创建了一个条件表单,需要在单击提交后定向到特定产品页面。这可能与此代码有关吗?我无法弄清楚如何将数组值链接到 URL 变量。

Here's the JSFiddle

a=new Array("V1-1: 1/4-4 900-4500#", "V1-1 Light-Weight Compact Solution", "V1-2: 1/2-36 150-600#","V1-3: 1/2-2, 150-600#","V1-4: 4-36 900-4500#");
b=new Array('NexTech® R Series Valves','NexTech® E Series Valves','TrunTech® Valves', 'PulseJet Valves');
c=new Array('Coking Isolation Valves','Coking Switch Valves');
d=new Array('Three-Way Valves','Four-Way Valves');
e=new Array('IsoTech®');
f=new Array('Xactrol® Mark I Valves', 'Xactrol® Mark II Valves', 'Xactrol® Mark III Valves');
g=new Array('PulseJet Valves','Ecopack®');
h=new Array('AbrasoCheck® Slurry Check Valves', 'AbrasoTech® Slurry Ball Valves');
i=new Array('Electronic Relief Valves');
j=new Array('ValvXpress® Automated Valve Packages');
k=new Array('Acid Injection Valves');
l=new Array('Double Block-and-Bleed Valves');
m=new Array('Turbine Bypass System');
n=new Array('Check Valves');
o=new Array('ValvXpress®','EcoPack®','ValvPerformance Testing®','Slurry Valves','Acid Injection Valves','Double Block-and-bleed Valves','Rhinoite® Hardfacing','Switch Valves','HVOF RiTech®','Cryogenic Valves');

populateSelect();

$(function() {

      $('#cat').change(function(){
        populateSelect();
    });

});


function populateSelect(){
    cat=$('#cat').val();
    $('#item').html('');


    if(cat=='a'){
        a.forEach(function(t) { 
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='b'){
        b.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='c'){
        c.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='d'){
        d.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='e'){
        e.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='f'){
        f.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='g'){
        g.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='h'){
        h.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }


    if(cat=='i'){
        i.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='j'){
        j.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='k'){
        k.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='l'){
        l.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='m'){
       m.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='n'){
        n.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }

    if(cat=='o'){
        o.forEach(function(t) {
            $('#item').append('<option>'+t+'</option>');
        });
    }





} 

【问题讨论】:

  • 每个数组中的每个条目是否都有一个 url?
  • 有这个代码吗?不,因为这段代码没有任何指示每个数组项的 URL 应该是什么。
  • @MikeMcCaughan 我认为这是关于“......弄清楚如何将数组值链接到 URL 变量......”的问题
  • @cske 我回答了帖子中唯一的问题:这可能与这段代码有关吗?.
  • @gavin 是的,每个产品都有它唯一的 URL。

标签: javascript jquery html arrays conditional


【解决方案1】:

您可以使用已有的标记将这些选定的值传递到产品页面,只需在表单中添加一个操作

<form action="yourpageurl" method="get">

您需要编写您的产品页面以动态显示任何必要的信息或根据传递的参数进行重定向。由于我们选择了上面的 get 方法,参数将作为查询字符串的一部分(url 的一部分)传递,但您也可以使用 POST。

【讨论】:

    【解决方案2】:

    我想我会采用这种方法。存储一个对象数组,每个对象都包含产品名称和该产品的相应 url。然后(假设您使用的是表单)您可以将表单的操作更改为所选选项的值。

    附注:建议使用括号表示法 ([]) 而不是 new Array()。您可以阅读更多关于此here 和其他来源的信息。此外,由于您在 populatSelect 函数中时您的 cat 只会是一个值,因此您应该使用 if..else if..else if.. 结构。在匹配的情况下,您将完全离开if..else if 表达式,从而节省时间。而如果您保留if..if..if..,即使您立即找到匹配项,您也必须评估所有这些。

    编辑:您绝对应该遵循其他一些答案正在使用的概念(即使用字典,这将允许您在没有所有if 检查的情况下检索正确的类别)。

    var cats = {
      a: [
           { product: 'V1-1: 1/4-4 900-4500#', url: '<product url>' },
           { product: 'V1-1 Light-Weight Compact Solution', url: '<product url>' },
           { product: 'V1-2: 1/2-36 150-600#', url: '<product url>' },
           { product: 'V1-3: 1/2-2, 150-600#', url: '<product url>' },
           { product: 'V1-4: 4-36 900-4500#', url: '<product url>' }
      ],
      b: [
           { product: 'NexTech® R Series Valves', url: '<product url>'},
           { product: 'NexTech® E Series Valves', url: '<product url>' },
           { product: 'TrunTech® Valves', url: '<product url>' },
           { product: 'PulseJet Valves', url: '<product url>' }
      ],
    
    // same for the rest of your categories
    };
    
    populateSelect();
    
    $(function() {
        $('#cat').change(function(){
            populateSelect();
        });
    });
    
    
    function populateSelect(){
        var cat = $('#cat').val();
        $('#item').html('');
    
        appendProducts(cats[cat]);
    }
    
    function appendProducts(arr) {
        arr.forEach(function(t) {
                $('#item').append('<option value="' + t.url + '">'+ t.product +'</option>');
            });
    }
    
    $('form').submit(function() {
        this.action = $('select').find(':selected').val();
    });
    

    【讨论】:

    • 我将所有代码都放入该格式,条件下拉菜单可以工作,但 URL 不能。可能与提交按钮有关吗? jsfiddle.net/r7MN9/1980
    • method="POST" 属于表单元素。由于 jsfiddle 的限制,不太确定您还有哪些其他问题。网址不起作用怎么办?
    【解决方案3】:

    首先,您违反了DRY principle。与其为每组产品设置单独的变量,不如将它们存储在某种字典结构中,例如对象。

    这将是我的第一次修订

    var dict = {
        a: ["V1-1: 1/4-4 900-4500#", "V1-1 Light-Weight Compact Solution", "V1-2: 1/2-36 150-600#","V1-3: 1/2-2, 150-600#","V1-4: 4-36 900-4500#"],
        b: ['NexTech® R Series Valves','NexTech® E Series Valves','TrunTech® Valves', 'PulseJet Valves'],
        c: ['Coking Isolation Valves','Coking Switch Valves'],
        d: ['Three-Way Valves','Four-Way Valves'],
        e: ['IsoTech®'],
        f: ['Xactrol® Mark I Valves', 'Xactrol® Mark II Valves', 'Xactrol® Mark III Valves'],
        g: ['PulseJet Valves','Ecopack®'],
        h: ['AbrasoCheck® Slurry Check Valves', 'AbrasoTech® Slurry Ball Valves'],
        i: ['Electronic Relief Valves'],
        j: ['ValvXpress® Automated Valve Packages'],
        k: ['Acid Injection Valves'],
        l: ['Double Block-and-Bleed Valves'],
        m: ['Turbine Bypass System'],
        n: ['Check Valves'],
        o: ['ValvXpress®','EcoPack®','ValvPerformance Testing®','Slurry Valves','Acid Injection Valves','Double Block-and-bleed Valves','Rhinoite® Hardfacing','Switch Valves','HVOF RiTech®','Cryogenic Valves']
    };
    
    $(function() {
        // attach an 'change' event handler
        // THEN trigger the event handler to call the function from the start
        $('#cat').change(populateSelect).trigger('change');
    });
    
    function populateSelect() {
        // this refers to the current element
        // get the selected value
        var cat = this.value;
        // always a good idea to cache your element that you will be re-using (maybe move it outside the function too)
        var items = $('#item');
    
        items.html('');
        // check if there are products associated with the selected value
        if (dict.hasOwnProperty(cat)) {
            // show products
            dict[cat].forEach(function(product) { 
                items.append('<option>' + product + '</option>');
            });
        }
    }
    

    现在,就您的实际问题而言。我们可以修改数组,使其也包含一个 url。为简单起见,您可以拥有数组数组,例如

    a: [["V1-1: 1/4-4 900-4500#", "url"], ["V1-1 轻型紧凑型 解决方案", "url"], ...]

    或对象数组以提高可读性,例如

    a: [{ name: "V1-1: 1/4-4 900-4500#", url: "url" }, { name: "V1-1 轻量级紧凑型解决方案", url: "url"}, ...]

    这是我使用对象数组的第二次修订。 (我缩短字典只是为了显示插图)。

    var dict = {
        a: [
            { 
                name: "V1-1: 1/4-4 900-4500#",
                url: "http://www.bing.com"
            },
            {
                name: "V1-1 Light-Weight Compact Solution", 
                url: "http://www.google.com"
            },
            {
                name: "V1-2: 1/2-36 150-600#",
                url: "http://www.yahoo.com"
            },
        ],
        b: [
            {
                name: 'NexTech® R Series Valves',
                url: 'http://www.nike.com'
            },
            {
                name: 'NexTech® E Series Valves',
                url: 'http://www.walmart.com'
            }
        ],
        c: [{
            name: 'Coking Isolation Valves',
            url: 'http://www.adidas.com'
        }],
    };
    
    $(function() {
        // cache element so that you don't re-search the DOM multiple times
        var $items = $('#item');
    
        $('#cat').change(populateSelect).trigger('change');
        $('#goto').click(redirectToURL);
    
        // place the functions within the document.ready so that they have access to the cached elements
        function populateSelect() {
            $items.html('');
            if (dict.hasOwnProperty(this.value)) {
                dict[this.value].forEach(function(product) {
                    // you can store the URL in HTML5-data attribute to use it later
                    $items.append('<option data-url="' + product.url + '">' + product.name +'</option>');
                });
            }
        }
    
        function redirectToURL() {
            // get the URL from the selected option's data-url and redirect to it
            window.location.href = $items.find(':selected').data('url');
        }
    });
    

    从技术上讲,您不是在“提交”表单,而只是“重定向”——所以我不会使用提交按钮,而只是使用普通按钮。

    <input type="button" id="goto" value="submit">
    

    下面是最终修订版的demo。你得修字典。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-03
      • 2016-08-15
      • 2014-07-17
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 2020-12-19
      相关资源
      最近更新 更多