简体   繁体   English

Javascript-基于动态填充的下拉菜单的url

[英]Javascript - Goto url based on dynamically populated drop down

I've created a condition form that needs to direct to a specific product page after clicking submit. 我创建了一个条件表单,该表单需要在单击“提交”后直接定向到特定的产品页面。 Is that possible to do with this code? 这可能与这段代码有关吗? I'm having trouble figuring out how to link the array values to a URL variable. 我在弄清楚如何将数组值链接到URL变量时遇到麻烦。

Here's the JSFiddle 这是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>');
        });
    }





} 

First, you are violating the DRY principle . 首先,您违反了DRY原则 Instead of having separate variables for each set of products, store each of them in a sort of dictionary structure such as an object. 不必为每个产品集使用单独的变量,而是将它们中的每一个存储在一种字典结构(如对象)中。

This would be my first revision . 这将是我的第一次修订

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>');
        });
    }
}

Now, in terms of your actual problem. 现在,就您的实际问题而言。 We can modify the arrays, so that it also includes a url. 我们可以修改数组,使其也包含一个URL。 You could have arrays of arrays for simplicity eg 为了简单起见,您可以使用数组的数组

a: [["V1-1: 1/4-4 900-4500#", "url"], ["V1-1 Light-Weight Compact Solution", "url"], ...] a:[[“ V1-1:1 / 4-4 900-4500#”,“ url”],[“ V1-1轻巧紧凑解决方案”,“ url”],...]

or arrays of objects for readability eg 或对象数组以提高可读性,例如

a: [{ name: "V1-1: 1/4-4 900-4500#", url: "url" }, { name: "V1-1 Light-Weight Compact Solution", url: "url"}, ...] a:[{名称:“ V1-1:1 / 4-4 900-4500#”,网址:“ url”},{名称:“ V1-1轻型紧凑型解决方案”,网址:“ url”}, ...]

So here's my second revision using arrays of objects. 所以这是我第二次使用对象数组的修订版 (I shorten the dictionary just to show illustration). (我只是为了显示插图而缩短字典)。

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');
    }
});

Technically, you are not "submitting" a form but just "redirecting" -- so I would not use a submit button but just an ordinary button. 从技术上讲,您不是在“提交”表单,而是在“重定向”-因此,我不会使用“提交”按钮,而只会使用普通按钮。

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

Below is a demo of the final revision. 以下是最终版本的演示 You'll have to fix the dictionary. 您必须修复字典。

You can pass these selected values to a product page using the markup you already have, just add an action to the form 您可以使用已有的标记将这些选定的值传递到产品页面,只需在表单中添加一个操作即可

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

You need to write your product page to dynamically show whatever information is necessary or redirect based on the parameters passed through. 您需要编写产品页面以动态显示所需的任何信息,或者根据传递的参数进行重定向。 As we have selected the get method above, the parameters would be passed as part of a query string (part of the url) but you could also use POST. 当我们选择上面的get方法时,参数将作为查询字符串(URL的一部分)的一部分传递,但是您也可以使用POST。

I think that I would take this approach. 我认为我会采用这种方法。 Store an array of objects, each of which contain the product name and the appropriate url for that product. 存储一个对象数组,每个对象都包含产品名称和该产品的相应URL。 Then (assuming you are using a form) you can change the action of form to the value of the selected option. 然后(假设您使用的是表单)可以将表单的操作更改为所选选项的值。

Side notes: It's recommended to use the bracket notation ( [] ) instead of new Array() . 注意事项:建议使用方括号( [] )代替new Array() You can read more about this here and at other sources. 您可以在这里和其他来源阅读有关此内容的更多信息。 Also, since your cat will only ever be one value when you're in the populatSelect function, you should use the if..else if..else if.. structure. 另外,由于当您使用populatSelect函数时, cat只会成为一个值,因此应使用if..else if..else if..结构。 In the case of a match, you will leave the if..else if expression completely, saving time. 在匹配的情况下,您将完全保留if..else if表达式,从而节省了时间。 Whereas if you kept if..if..if.. , you would have to evaluate all of them even if you found a match right away. 而如果您保留if..if..if.. ,则即使您立即找到匹配项,也必须评估所有这些值。

EDIT : You should definitely follow the concepts that some of the other answers are using (namely using a dictionary, which will allow you to retrieve the correct category without all the if checks). 编辑 :您绝对应该遵循其他一些答案使用的概念(即使用字典,这将使您无需进行所有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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM