我想在javascript变量中将文本存储在p标签下,然后在输入字段中显示

时间:2018-02-09 18:25:04

标签: javascript jquery html

我希望在javascript varible中的p标签中存储文本,然后在输入字段中显示文本。

<p id="txt" onclick="check();">yes i am stroe in js variable</p>
<input id="show" type="text" name="" disabled="">

    <script type="text/javascript">
function check() {
    var input = document.getElementById("txt").text;

    document.getElementById("show")=input.value;
}
</script>

3 个答案:

答案 0 :(得分:2)

请参阅此fiddle

要获取<p>内的内容,您必须使用innerHTML而不是value

docs

中详细了解innerHTML

因此,您的script应该重写为

function check() {
    var input = document.getElementById("txt");
    document.getElementById("show").value=input.innerHTML;
}

&#13;
&#13;
function check() {
    var input = document.getElementById("txt");
    document.getElementById("show").value=input.innerHTML;
}
&#13;
<p id="txt" onclick="check();">yes i am stroe in js variable</p>
<input id="show" type="text" name="" disabled="">
&#13;
&#13;
&#13;

或者

如果您想使用 jQuery解决方案

按如下方式更改script

function check() {
    var input = $("#txt");
    $("#show").val(input.text());
}

请参阅下面的代码段。

&#13;
&#13;
function check() {
    var input = $("#txt");
    $("#show").val(input.text());
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="txt" onclick="check();">yes i am stroe in js variable</p>
<input id="show" type="text" name="" disabled="">
&#13;
&#13;
&#13;

答案 1 :(得分:0)

document.getElementById(&#39; show&#39;)。value = input;

答案 2 :(得分:0)

html:

<p id="PTag">Hello :D</p>
<a id="Btn">click me</a>

在脚本中使用文字

<script>
  $('#Btn').click(function () {
     var hello= $("#PTag").html($("#text").val())[0].innerHTML; 
     alert(hello)
  })
</script>

结果 ====== >>>> 你好:D