跨浏览器innerText用于设置值 [英] Cross-browser innerText for setting values

查看:88
本文介绍了跨浏览器innerText用于设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说下面的代码:

<html>
  <head></head>
  <body>
   <div id="d">some text</div>

  <script type="text/javascript">
    var d = document.getElementByid('d');
    var innerText = d.innerText || d.textContent;

    innerText = 'new text';
  </script>
  </body>
</html>

并且我想更改id ='d'的div标签的文本值。不幸的是,上面的块代码不工作,文本内容不会改变。

And I want to change text value for the div tag with id='d'. Unfortunately the block code above doesn't work and the text content doesn't change.

如果做以下食谱,它会工作:

It works if do the following recipe:

if (d.innerText) d.innerText = 'new text';
else d.textContent = 'new text';

但我不喜欢上面的食谱,因为它不紧凑。

But I dont like the recipe above because it's not compact.

您有什么建议,为什么第一种方法不起作用?

Have you any suggestions why the first approach doesn't work?

推荐答案

可以抓取属性并使用

var text = ('innerText' in d)? 'innerText' : 'textContent';
d[text] = 'New text';

这篇关于跨浏览器innerText用于设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆