使用Javascript document.write构建字符串 [英] String building with Javascript document.write

查看:132
本文介绍了使用Javascript document.write构建字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从JavaScript编写div元素。我希望使用document.write()编写如下代码:

I am trying to write a div element from javascript. I want the line written as follows, using document.write():

<div class="Square15px" onmouseover="changeColor('boxid')"></div>

我调用写div元素的函数:

I call the function that writes the div element with:

<script type="text/javascript">
      colorPicker("box1");
 </script>

我尝试了document.write()方法,以几种不同的方式构建字符串,例如:

I have tried the document.write() method, building the string several different ways such as:

function colorPicker(box) {
    var box = document.getElementById(box);
    var boxid = box.id;
    var AquaStr1 = '<div class="AquaSquare15px" onmouseover="changeColor("';
    var AquaStr2 = '")></div>';

    var AquaString = AquaStr1.concat(boxid, AquaStr2);
    document.writeln(AquaString);
}

我也尝试使用+作为concat运算符以多种方式拆分字符串。在boxid的末尾,该字符串生成不正确。无论如何编写代码块,我都得到相同的结果:

I have also tried splitting up the string many different ways using + as concat operator. The string builds incorrectly at the end of boxid. I get the same result no matter how I write the code block:

<div class="AquaSquare15px" onmouseover="changeColor(" box1?)=""/>

我似乎在这里看不到我的错误,我已经查看了所有可以找到的帮助。除了引号和box1之间的空格外,一切正确,直到神秘的问号为止。
我查看了IE9开发人员工具(F12)的结果。我不是一位经验丰富的程序员,所以我怀疑自己错了

I just can't seem to see my error here, I have reviewed all of the help I can find. With the exception of the space between the quote and box1, everything is correct up until the mysterious question mark. I reviewed the results from IE9 developer tool (F12). I am not an experienced programmer, so I suspect I am in error somehow.

推荐答案

在评论部分中进行了修改:您不应使用 document.write
但是,您的字符串连接出错了。相反,请尝试以下操作:

As pointed out in the comments section: you shouldn't use document.write. But nevertheless, your string concatenation went wrong. Try this instead:

function colorPicker(box) {
    var boxid = document.getElementById(box).id;
    var aquaStr = '<div class="AquaSquare15px" onmouseover="changeColor(\''+boxid+'\')"></div>';

    document.writeln(aquaStr);
}

这篇关于使用Javascript document.write构建字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆