【问题标题】:style a div using escaped URL parameters使用转义的 URL 参数设置 div 样式
【发布时间】:2014-05-08 18:12:31
【问题描述】:

我是 javascript 新手,我不完全了解如何修改此代码以设置 div 样式:

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( color, background ) {
      document.body.innerHTML += color + background ;
    });
}

http://jsfiddle.net/Qmu5L/4/


也可以在这里查看:escaped URL parameters statements if else switch

【问题讨论】:

  • style a div是什么意思
  • 您可以使用$(body).css('color',color)。看看here

标签: javascript


【解决方案1】:

.each(function(){}); 函数中的变量不是自定义的,它们始终是 id 和 value。

你的函数应该是这样的:

$.each(hash, function (id, value) {
    test_div.style[id] = value;
});

这是FIDDLE

基本上发生了什么,您的哈希数组包含两个对象:

1) 颜色 {value = "red"}

2) 背景 {value = "黄色}

每个函数迭代都认为,id 将是第一次 color 广告第二次 background

第一次是"red",第二次是"yellow"

例如,对于第一次迭代,id = 'color' 和 value ='red' 它将产生:

test_div.style["color"] = "red";

【讨论】:

【解决方案2】:

使用 javascript 函数 styleDiv 您可以传递样式的 url 字符串 (style=value) 和目标 (DOM 元素标记名称、id、类)。它会找到这些目标,并设置样式。

感谢 Banana 使用 element.style[property] = value,我不知道。

jsFiddle link

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Style a Div</title>

  <script type='text/javascript' src='http://code.jquery.com/jquery-git2.js'></script>


  <style type='text/css'>
    input[type=text] {width: 300px;}
  </style>



<script type='text/javascript'>//<![CDATA[ 
$(function(){
styleDiv = function(paramString, target){
    param = paramString.split('&');
    if (param.length < 1)
        return false;
    for(i=0; i< param.length; i++){
        val = param[i].split('=');
        //jQuery(target).css(unescape(val[0]),unescape(val[1]));
        targets=document.querySelectorAll(target);
        for (t=0; t < targets.length; t++){
            targets[t].style[unescape(val[0])] = unescape(val[1]);
        }
    }
}

jQuery('#cmdSetStyle').click(function(e){
    console.log(styleDiv(jQuery('#txtParamStyle').val(),'#target'));
    return false;    
});

});//]]>  

</script>


</head>
<body>
  <form id="frmSendStyle" method="get">
    <input type="text" id="txtParamStyle" value="color=red&background=yellow" />
    <input type="button" id="cmdSetStyle" value="Set Style" />
</form>

<div id="target">
    Hello world
</div>

</body>


</html>

【讨论】:

猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 2014-02-10
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
  • 1970-01-01
  • 2011-12-14
  • 2011-08-17
相关资源
最近更新 更多