我有一个看起来像这样的下拉列表:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
&#13;
如何根据网址预先将值填充到saab中。我在不同的页面上有链接,每个选项都有一个链接。我希望人们能够选择链接&#34;萨博&#34;,有些人如何通过网址传递,并使#34; saab&#34;加载此表单的页面时选择。 如果可能,最好是java脚本解决方案吗?
答案 0 :(得分:0)
获取window
的{{1}}并解析location
应该可以解决问题。然后,您只需在pathname
下拉列表中的相应selected
上设置option
属性。
注意:此代码不需要任何依赖项。
select
function main() {
var url = new URLParser(window.location);
var path = url.pathname;
//Say our pathname is "/saab"
path = '/saab';
var selectEl = document.getElementById('make');
for (var i = 0; i < selectEl.length; i++) {
var optionEl = selectEl.options[i];
if (optionEl.value === path.substr(1)) {
optionEl.setAttribute('selected', 'selected');
}
}
}
// I wrote this URL parser a while back. It should be cross-browser safe.
// http://stackoverflow.com/a/27964708/1762224
var URLParser = (function(document) {
var PROPS = 'protocol hostname host pathname port search hash href'.split(' ');
var self = function(url) {
this.aEl = document.createElement('a');
this.parse(url);
};
self.prototype.parse = function(url) {
this.aEl.href = url;
if (this.aEl.host == "") {
this.aEl.href = this.aEl.href;
}
PROPS.forEach(function(prop) {
switch (prop) {
case 'hash':
this[prop] = this.aEl[prop].substr(1);
break;
default:
this[prop] = this.aEl[prop];
}
}, this);
if (this.pathname.indexOf('/') !== 0) {
this.pathname = '/' + this.pathname;
}
this.requestUri = this.pathname + this.search;
};
self.prototype.toObj = function() {
var obj = {};
PROPS.forEach(function(prop) {
obj[prop] = this[prop];
}, this);
obj.requestUri = this.requestUri;
return obj;
};
self.prototype.toString = function() {
return this.href;
};
return self;
})(document);
main();