escaped URL parameters statements if else switch

后端 未结 2 579
挽巷
挽巷 2021-01-27 06:07

There is a little problem with this code:

function getParameters() {
  var searchString = document.getElementById(\'input1\').value,
      params = searchString.         


        
相关标签:
2条回答
  • 2021-01-27 06:54

    in your line

    if(val[0] == "class")
    

    you are only checking the first element in your val array.

    what you would want to do, is iterate through all the hash objects and simply check the attribute like this:

    function getParameters() {
      var searchString = document.getElementById('input1').value,
          params = searchString.split("&"),
          hash = {};
    
      if (searchString == "") return {};
      for (var i = 0; i < params.length; i++) {
        var val = params[i].split("=");
        hash[unescape(val[0])] = unescape(val[1]);
      }
        console.log(hash);
      //return hash;
        $.each(hash, function( attribute, value ) {
    
            if(attribute=="color"){
                test_div.style[attribute]=value;
            }
            else if(attribute=="src"){
                alert(attribute);
                test_div.setAttribute(attribute,value);
            }
        });
    }
    

    here is a working FIDDLE

    0 讨论(0)
  • 2021-01-27 06:55

    Maybe you want something like this:

    var test_div = $('#test_divs_id');
    
    for (var i = 0; i < params.length; i++) {
     var val = params[i].split("=");
    
     var key = unescape(val[0]);
     var val = unescape(val[1]);
    
     switch(key) {
    
      case 'class':            // treat 'class' key by ...
       test_div.addClass(val); // ... adding the value as a class
       break;
    
      case 'src':              // treat 'src' key,
      case 'href':             // treat 'href' key, maybe more ...
       test_div.attr(key, val); //... by adding as an attribute with value
       break;
    
      default:                 // all other keys...
       test_div.css(key, val); // ... are assumed css style names with value
       break;
     }
    

    EDIT: Extended the switch with the examples + possibly more attributes

    0 讨论(0)
提交回复
热议问题