【问题标题】:Cannot get element by id or className无法通过 id 或 className 获取元素
【发布时间】:2013-02-20 12:02:37
【问题描述】:

我有一个包含多个 div 和其他元素的 iframe。我想将焦点设置到几个文本框中的一个文本框。

我用过:

    a = iFrameObj.contentWindow.document.getElementById('myTxtBox');

   But here, a is null;

我可以使用以下代码访问文本框对象;

var myTextBox = iFrameObj.contentWindow.document.getElementsByTagName('input')[52];

但我想使用更通用的方法来获取对象而不是硬编码索引。

由于这个文本框有唯一的类名,我尝试了以下代码:

var myTextBox = iFrameObj.contentWindow.document.getElementsByClassName('rgtxt')[0];

但我出错了:

"Object does not support this property or method"

我的文本框的 HTML 是:

<input name="myTxtBox" type="text" class="rgtxt" id="myTxtBox" value="hello" style="display:block;color:Black;background-color:rgb(240, 241, 241);" readonly="readonly" />

有人可以帮助 iFrame 中这两种方法有什么区别吗?

【问题讨论】:

标签: javascript jquery dom iframe getelementsbyclassname


【解决方案1】:

试试这个

 $("#youriFrameID").contents().find("input.rgtxt").focus();

使用 jquery...

【讨论】:

    【解决方案2】:

    检查一下

    $("input[id$='myTxtBox']").val()
    

    【讨论】:

      【解决方案3】:

      getElementsByClassName 方法只在 IE9+ 上可用,所以错误信息是正确的(虽然不是很清楚),在 IE8 上没有这种方法。

      您可以在此处阅读更多信息:http://msdn.microsoft.com/en-us/library/ie/ff975198(v=vs.85).aspx

      【讨论】:

        猜你喜欢
        • 2012-07-20
        • 1970-01-01
        • 2017-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-21
        • 1970-01-01
        相关资源
        最近更新 更多