为什么 Chrome 在使用书签时更新正文而不是文本区域值
Why is Chrome updating the body instead of the textarea value when using a bookmarklet?
我有最新的Chrome,我想用书签更新textarea
字段,如下所示:
javascript:document.getElementById("<here comes the ID>").value="test";
Chrome 始终使用值"test"(来自上面的示例)更新元素body
,而不是textarea
您可以通过转到 http://reference.sitepoint.com/html/textarea/demoframe 并使用所述页面的textarea
ID 或通过下面的堆栈代码段执行书签来测试这一点:
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
作为最后一个命令可以解决问题。但是为什么?似乎只有书签才会有这种行为。
这是
预期行为
如果运行书签并且其返回值不是undefined
则浏览器将页面内容替换为返回值是标准行为。在您的示例中,这是"测试"。
当浏览器遵循javascript:URI时,它会计算URI中的代码,然后用返回的值替换页面的内容,除非返回的值未定义。
JavaScript URIs (Mozilla Developer Network - void operator)
为什么您的第二个版本有效?
这似乎是Chrome中的一个错误(问题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>
相关文章:
- onkeyup无法动态创建多个文本区域
- 具有所有样式的文本正在复制到可编辑文本区域
- 在文本区域POST后解码JSON
- 在文本区域中使用jQuery.text()保持换行符
- ng在下拉列表和文本区域提交
- 将文本插入光标所在的文本区域
- 离开页面导航后保留文本区域内容
- Javascript-在文本区域中断,但不在段落中中断
- 当选择值x时,Javascript需要在正确的位置显示文本区域,从而循环通过具有选择选项的表单
- 测试文本区域中的特定文本格式
- 文本编辑后,append函数不适用于文本区域
- 如何在ReactJs中链接下拉列表和文本区域
- I'我试图在文本区域中进行特定的输入,调用特定的javascript函数,但没有成功;不起作用
- 使用JSON文件中的变量(字符串)填充文本区域
- JavaScript-如果以前不存在文本,如何从文本区域删除新行
- 如何在php中创建一个函数,该函数与文本区域一起工作,通过输入类似[color:red]的内容来打印具有等效颜色的文本
- 如何为动态创建的文本区域中输入的值更新ng模型
- 延迟高亮显示文本区域中的文本
- 将字母添加到文本区域的末尾
- TinyMCE在新添加的文本区域