如何在JavaScript textarea框中使用JavaScript函数的输出作为字符串?

时间:2016-06-02 18:27:36

标签: javascript jquery html

我一直在创建一个配置文件制作程序,我想将这个JS函数的输出用作textarea框内的简单字符串文本,用户可以使用“复制到剪贴板”按钮进行复制。有任何想法,请尽快通知我。这是我目前的代码:

<!--HTML-->
<!--Button Code-->
<button onclick="copyprofile()">Copy to clipboard</button><br>   
<!--Textarea Code-->
<textarea id="text" cols="60" rows="13">I want output of createProfile() to be here</textarea><br>

//Javascript
function createProfile(){
    var fn,ln,a,fc,fs,ff,profile;
    fn = prompt("Please enter your first name","Enter first name here");
    ln = prompt("Please enter your last name","Enter last name here");
    a = prompt ("Please enter your age","Enter age here");
    fc = prompt("Please enter your favourite colour","Enter favourite color here");     
    fs = prompt("Please enter your favourite sport","Enter favourite sport here");
    ff = prompt("Please enter your favourite food","Enter favourite food here");
    profile = ("Name: " + fn + " " + ln + "<br>Age: " + a + "<br>Favourite colour: " + fc + "<br>Favourite sport: " + fs + "<br>Favourite food: " + ff);
    return profile;
}
function copyProfile(){
    var text = document.getElementById('text');
    var range = document.createrange();

    range.selectNode(text);
    window.getSelection().addRange(range);
    document.execCommand(copy);
}

如果您对如何实现这一点有任何想法或想法,请告诉我

1 个答案:

答案 0 :(得分:1)

由于您已将所有内容保存在分配给profile的字符串中,因此只需引用要更新的元素并将其指定为value

在javascript中:

document.getElementById("text").value = profile;

如果您希望保留换行符,则除<br>之外,您需要执行textarea以外的其他操作,因为\n通常不会呈现HTML。我建议做carriage return or line feedprofile = ("Name: " + fn + " " + ln + "\nAge: " + a + "\nFavourite colour: " + fc + "\nFavourite sport: " + fs + "\nFavourite food: " + ff);;

copyProfile

这是一个带有示例https://jsfiddle.net/x1w1t8ux/

的JSFiddle

<强>更新

我花了一些时间来查看你的其余代码,因为你说它仍然无法正常工作。您的document.createrange()函数有几个错误。如果您在尝试运行这些功能时打开了开发人员控制台,则会看到错误消息:

  

未捕获的TypeError:document.createrange不是函数

你排队document.execCommand(copy);不是一个功能。你需要将它归为document.createRange()

修复该错误后,尝试再次运行代码将在控制台中显示另一个错误:

  

未捕获的ReferenceError:未定义复制

在这一行copy中,您引用了一个名为document.execCommand('copy');的变量。该变量不存在,也不是您正在寻找的变量。您希望将字符串 copy 传递给函数execCommand。它应该看起来像<button onclick="copyProfile()">Copy to clipboard</button>(带引号,就像你在JavaScript中识别字符串一样。

在您的HTML中,当您点击“复制到剪贴板”按钮copyprofile时,它会抛出错误

  

未捕获的ReferenceError:未定义copyprofile

您没有名为copyProfile的功能,您有一个名为createProfile()的功能。函数名称区分大小写。我建议坚持一致的命名约定(例如驼峰案例)

最后,您的代码中没有位置调用函数<?xml version="1.0" encoding="utf-8"?> <urlrewrite> <rule> <condition type="remote-addr" operator="notequal">0:0:0:0:0:0:0:1%0</condition> <condition type="remote-addr" operator="notequal">127.0.0.1</condition> <set type="status" last="true">403</set> <to>null</to> </rule> </urlrewrite> 。所以我在测试中将它创建为第二个按钮。