js:innerHTML與innerText||textContent

用法


  • DOM節點.innerHTML

獲取整個節點內的所有內容,包括HTML標簽,比如下面這段代碼:

<ul id="header-unlogin">
    <li id="header-signin"><a href="#1">登錄</a></li>
    <li id="header-signup"><a href="#2">注冊</a></li>
</ul>

$("#header-unlogin").innerHTML的內容是:
<li id="header-signin"><a href="#1">登錄</a></li> <li id="header-signup"><a href="#2">注冊</a></li>

  • DOM節點.innerText/DOM節點.textContent(注意大小寫)
    獲取整個節點內的所有去除HTML標簽的文字內容,比如上面的那段代碼:

$("#header-unlogin").innerText的內容是:
登錄注冊

兼容


  • innerHTML全瀏覽器兼容(所有的瀏覽器都支持的屬性)
  • innerText兼容IE、Safari、Opera和Chrome
  • textContent兼容firefox

總結


需要使用innerText||textContent時,寫一個判斷就好:

if(obtn.textContent){
            obtn.textContent=="登錄"?oLoginHeader_spans[0].id="login-selected":oLoginHeader_spans[1].id="login-selected";
        }else{
            obtn.innerText=="登錄"?oLoginHeader_spans[0].id="login-selected":oLoginHeader_spans[1].id="login-selected";
        }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容