在输入值中放置一个完整的标记

时间:2015-04-11 15:22:15

标签: javascript jquery html

我正在尝试将一些标记放入输入值。这是我的代码:

<html>
    <head>
        <title>Test</title>
    </head>
    <script src="jquery-1.10.2.js"></script>
    <script>
        $(document).ready(function(){
            var n_cours = $("span").size();
            console.log(n_cours);
            for(var v=0;v<n_cours;v++){
                var ok = $("span:eq("+v+")")[0];
                var ok2 = $("span:eq("+v+")").text();
                var html = "<tr><td><input value='"+ ok +"'></td><td><input value='"+ok2+"'></td></tr>";
                $("table").append($(html));
            }
        });
    </script>
    <body>
        <div>
            <span>1stackoverflow</span>
            <span>2stackoverflow</span>
            <span>3stackoverflow</span>
        </div>
        <table border="1Px"></table>
    </body>
</html>

我想要的输出是:

----------------------------------------------------------
| <span>1stackoverflow</span>    | 1stackoverflow        |
----------------------------------------------------------
| <span>2stackoverflow</span>    | 2stackoverflow        |
----------------------------------------------------------
| <span>3stackoverflow</span>    | 3stackoverflow        |
----------------------------------------------------------

但我得到了不同的结果:

----------------------------------------------------------
| [object HTMLSpanElement]    | 1stackoverflow        |
----------------------------------------------------------
| [object HTMLSpanElement]    | 2stackoverflow        |
----------------------------------------------------------
| [object HTMLSpanElement]    | 3stackoverflow        |
----------------------------------------------------------

如何让它显示HTML表示?

1 个答案:

答案 0 :(得分:4)

您可以使用outerHTML属性:

for(var v=0;v<n_cours;v++){
    var ok = $("span:eq("+v+")")[0].outerHTML;
    var ok2 = $("span:eq("+v+")").text();
    var html = "<tr><td><input value='"+ ok +"'></td><td><input value='"+ok2+"'></td></tr>";
    $("table").append($(html));
 }