gpt4 book ai didi

javascript - 为什么 Chrome 在使用小书签时更新正文而不是文本区域值?

转载 作者:行者123 更新时间:2023-11-28 06:18:41 24 4
gpt4 key购买 nike

我有最新的 Chrome,我想使用书签更新 textarea 字段,如下所示:

javascript:document.getElementById("<here comes the ID>").value="test";

Chrome 始终使用值“test”(来自上面的示例)而不是 textarea 更新元素 body

您可以通过访问http://reference.sitepoint.com/html/textarea/demoframe来测试这一点并使用上述页面的 textarea ID 或通过下面的 Stack Snippet 执行书签:

ul, li{
margin: 0;
padding: 0;
}
textarea {
margin-top: 10px;
width: 100%;
}
<ul>
<li><strong>Without the void operator:</strong> <a href="javascript:document.getElementById('testTextarea').value='test 1';">This link will replace the contents of the page with "test 1"</a></li>
</ul>
<textarea id="testTextarea">Content to be replaced</textarea>

所以我的问题是:为什么 Chrome 会更新 HTML 元素 body

3 月 1 日凌晨 2:11 编辑(UCT):
以下代码在 Chrome 中运行良好:

javascript:document.getElementById("<here comes the ID>").value="test"; true;

因此添加 true 作为最后一个命令可以解决该问题。但为什么?似乎只有小书签才会有这种行为。

最佳答案

这是预期行为

如果运行小书签并且其返回值不是未定义,则浏览器的标准行为是用返回值替换页面内容。在您的示例中,这是“测试”。

When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is undefined.

JavaScript URI ( Mozilla Developer Network - void operator )

为什么你的第二个版本可以工作?

这似乎是 Chrome ( Issue 407505 ) 中的错误,IE 和 Firefox 中的相同代码会产生预期的行为(即与第一个版本相同的结果)。

你能做什么?

  • 使用void运算符。这将确保 undefined 是相反返回

  • 更改第二个方法以返回 undefined 而不是 true

ul, li{
margin: 0;
padding: 0;
}
textarea {
margin-top: 10px;
width: 100%;
}
<ul>
<li><strong>With the void operator:</strong> <a href="javascript:void(document.getElementById('testTextarea').value='test 1');">This link will replace the contents of the textarea with "test 1"</a></li>
<li><strong>Returning undefined:</strong> <a href="javascript:document.getElementById('testTextarea').value='test 2';undefined;">This link will replace the contents of the textarea with "test 2"</a></li>
</ul>
<textarea id="testTextarea">Content to be replaced</textarea>

关于javascript - 为什么 Chrome 在使用小书签时更新正文而不是文本区域值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35724703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com