【问题标题】:Replace a button that loads a prompt by its result用结果替换加载提示的按钮
【发布时间】:2014-12-03 19:59:51
【问题描述】:

我有一个文本。在里面,我想问读者问题,答案将插入文本中的什么地方。我希望通过按钮提示问题,并在验证提示时让按钮消失。

所以我现在拥有的是:

Once upon a time in <button onclick="prompt('Where do you live?')">Where do you live?</button>, a very beautiful place…

它让我得到了我文本中的按钮,我想要的提示,但是当我点击确定后关闭提示时,如何获得这个提示的结果来替换按钮?

【问题讨论】:

    标签: javascript button text prompt


    【解决方案1】:

    这个onclick() 做我认为你想要的。

    Once upon a time in &lt;button onclick="this.outerText = prompt('Where do you live?');"&gt;Where do you live?&lt;/button&gt;, a very beautiful place…

    基本上,它将提示的值设置为按钮的outerTextouterText 替换整个按钮,而 innerText 会将其放置在按钮内,如果您愿意的话。它看起来像这样:

    Once upon a time in &lt;button onclick="this.innerText = prompt('Where do you live?');"&gt;Where do you live?&lt;/button&gt;, a very beautiful place…

    【讨论】:

    • 值得注意的是,这很容易受到 JavaScript 注入。
    • 你是什么意思,@JackieChiles?
    • 非常感谢,outerHTML 正是我想要的。
    • @Godisgood 运行您的代码 sn-p 并在提示符中输入&lt;img src='https://www.google.com/images/srpr/logo11w.png' onload='alert("Insert malicious code here");' /&gt; 之类的内容,您就会明白我的意思了。攻击者可以用恶意脚本替换无害的alert 代码。例如,如果该输入被保存到服务器并由另一个用户加载,则可能会从第二个用户那里窃取数据。这就是 Stack Snippets run in a separate domain 的原因之一。
    • @JackieChiles,我现在明白你的意思了。我用“文本”替换“HTML”。那个更好吗?他们现在不能放任何恶意,对吗?
    猜你喜欢
    • 2017-10-13
    • 1970-01-01
    • 2011-05-27
    • 2014-01-19
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多