【问题标题】:select() a textarea within an iframeselect() iframe 中的文本区域
【发布时间】:2012-05-20 20:40:13
【问题描述】:

我在 iframe 中有一个文本区域。我想在 JavaScript 中选择带有 onclick 事件的 textarea 文本。

例子:

I have an iframe.

The inner content of the iframe is this:
<textarea id="textarea" disabled onclick="selectthis()">
"content of textarea"
</textarea>

我想选择文本以便用户复制它:

I put this at the head of my page:

function selectthis() {
   document.getElementById('textarea').select();
}

但是当我点击textarea时,它并没有被选中。

【问题讨论】:

  • 我认为你必须先集中注意力。
  • document.getElementById('textarea') 至少你必须纠正拼写错误的方法名称

标签: javascript html iframe textarea


【解决方案1】:


getelementById 更改为getElementById。 JavaScript 区分大小写。

http://jsfiddle.net/DerekL/ArGhg/

另外,

<textarea id="textarea" onclick="selectthis">  <!--Nope-->
<textarea id="textarea" onclick="selectthis();">  <!--Yup!-->

更新

我看到你在那里做了什么。您不能在 已禁用 &lt;textarea&gt; 中选择文本。
http://jsfiddle.net/DerekL/ArGhg/2/

根据 Francisc 的评论,使用readonly 将解决问题。
http://jsfiddle.net/DerekL/ArGhg/3/

【讨论】:

  • 虽然Yup 也应该是Nope
  • @Francisc - 不应该真正使用内联onclick,但它仍然是正确的。
  • @PitaJ - 查看更新。您无法在禁用的textarea 中选择文本。
【解决方案2】:

你需要这个:

document.getElementById('textarea').select();

函数在 Javascript 中区分大小写,因此请确保正确大写所有内容(我将 egetElementById 大写。

【讨论】:

    【解决方案3】:

    函数selectthis 可能会产生一个错误,因为它找不到任何以textarea 为id 的元素。问题是您使用了document.getElementById(我修正了错字),但textarea 不属于document。 您必须访问 iframe 自己的文档对象,通常是这样的:

    var iframe = document.getElementsByTagName("iframe")[0];
    var ifrDoc = iframe.contentDocument;
    var textarea = ifrDoc.getElementById("textarea");
    textarea.select();
    

    注意:在 IE8 中您必须指定文档类型,而在早期版本中您可以使用 iframe.contentWindow.document 代替。

    【讨论】:

      猜你喜欢
      • 2010-11-29
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 2019-03-11
      • 2020-11-11
      • 1970-01-01
      相关资源
      最近更新 更多