【问题标题】:converting a [object HTMLCollection] into string in javascript将 [object HTMLCollection] 转换为 javascript 中的字符串
【发布时间】:2012-06-20 18:26:23
【问题描述】:

我正在尝试使用getElementByTagName 从 XML 文件中提取的数据,它返回 HTML Collection Object 但我需要这些数据来发送 REST 请求,因此我需要将 HTML 集合对象转换为字符串.怎么办?

这里有更多信息:

com_zimbra_om.prototype._responseHandler=
        function(response){
                try{
                    sid = response.xml.getElementsByTagName("session_id");
                    this.login_user();
                    }catch(e){
                            this._showErrorMsg(e);
                            }

使用此函数,我试图从 REST 响应中获取 session_id。这里sid(全局变量)是 HTML 集合对象。现在,当我尝试在下一个函数中使用它时:

com_zimbra_om.prototype.login_user = function(){
var url = selected_server + 'services/UserService/loginUser?SID=' +
                                    sid + '&username='+
                                    selected_username +
                                    '&userpass=' + 
                                    selected_password;
                var request_url = ZmZimletBase.PROXY + AjxStringUtil.urlComponentEncode(url);

所以我在这里使用sid,我需要它作为字符串。

那么我应该如何将 HTML 集合对象转换为字符串呢??

谢谢

【问题讨论】:

  • 这样一个集合的字符串表示应该是什么样子?请更精确并提供一些带有输入和输出的示例代码。
  • 我怀疑您是否从 XML 文档中获得了 HTMLCollection...
  • @Bergi document.getElementsByTagName("div") + "" 在 Firefox 中给出了这一点,请参阅 bugzilla.mozilla.org/show_bug.cgi?id=14869
  • 您也可以运行var a = DOMParser(); var xml = "<node></node>"; xml = a.parseFromString(xml, "application/xml" ); xml.getElementsByTagName("node") + ""; //"[object HTMLCollection]" 来查看它与 XML 文档没有什么不同。
  • @Esailija:好的,感谢提供错误链接。我也期望 NodeLists(因为它恰好在 Opera 中工作,例如 :-)

标签: javascript html rest zimbra


【解决方案1】:

有了这个信息,我只能去

var objectHTMLCollection = document.getElementsByTagName("div"),
    string = [].map.call( objectHTMLCollection, function(node){
        return node.textContent || node.innerText || "";
    }).join("");

【讨论】:

  • 我们能否将完整的 html 代码存储在字符串变量中,例如 var a ="<html><head></head><body></body></html>" 或字符串中的原始 html 代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 2017-09-16
  • 2011-06-14
相关资源
最近更新 更多