此代码存在一些问题:
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;
if(val[0] == "class"){ //alert(val[1]);
$.each(hash, function( attribute, value ) {
test_div.setAttribute(attribute,value);
});
}
else if(val[0] == "color"){ //alert(val[1]);
$.each(hash, function( attribute, value ) {
test_div.style[attribute]=value;
});
}
monitor_test_div.innerText = ccc.innerHTML;
}
取决于插入参数的顺序,它们会重复或不起作用......
style a div using escaped URL parameters
演示:JSFiddle 1
演示:JSFiddle 2
我想得到这个:
示例1:
输入:
opacity=0&src=link1&color=red&color=green&src=link2&height=200
输出:
<div src="link2" style="color: green;"></div>
示例2:
输入:
src=link1&color=red
或color=red&src=link1
输出:
<div src="link1" style="color: red;"></div>
答案 0 :(得分:0)
也许你想要这样的东西:
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;
}
编辑:使用示例扩展开关+可能更多属性
答案 1 :(得分:0)
在你的行
if(val[0] == "class")
您只检查val数组中的第一个元素。
您想要做的是迭代所有哈希对象,只需检查这个属性:
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);
}
});
}
这是一个有效的FIDDLE