JS/JQ 常用方法

获取form里面的内容

/**
* 获取对应form里面的值
 * @param formId
*/            
function getElements(formId) {  
  var form = document.getElementById(formId);  
  var str = '';
  // var elements = new Array();  
  var tagElements = form.getElementsByTagName('input');  
  for (var j = 0; j < tagElements.length; j++){ 
     // elements.push(tagElements[j].valueOf()); 
     console.log(tagElements[j].name);
     console.log(tagElements[j].value);
     var name = tagElements[j].name;
     var value = tagElements[j].value;
     if(str == '')
     {
         str += name+"="+value;
     }
     else 
     {
         str += "&"+name+"="+value;
     }
  } 
}  

获取当前url的参数且根据入参合并

/**
 * get参数和方法参数合并
 * @param params
 * @returns {string}
 */
function getQueryVariable(params)
{
    var searchArr = new Object();
    var str = '';
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    var paramsvars = params.split("&");
    if(query != '' && vars.length > 0)
    {
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            searchArr[pair[0]+""] = pair[1];
            for (var c=0;c<paramsvars.length;c++)
            {
                var pair1 = paramsvars[c].split("=");
                if(pair1[0] == pair[0])
                {
                    searchArr[pair[0]+""] = pair1[1];
                }
            }
        }
    }
    else
    {
        for (var c=0;c<paramsvars.length;c++)
        {
            var pair1 = paramsvars[c].split("=");
            searchArr[pair1[0]+""] = pair1[1];
        }
    }

    // 组合string
    for(var key in searchArr){

        if(str == '')
        {
            str = "?"+key+"="+searchArr[key];
        }
        else
        {
            str += "&"+key+"="+searchArr[key];
        }
    }

    return str;
}

你可能感兴趣的:(前端)