一个HTML元素镜像的另一个最优雅的方式是什么? [英] Most elegant way to have one HTML element mirror another?

查看:376
本文介绍了一个HTML元素镜像的另一个最优雅的方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个应始终包含相同内部HTML文本的HTML元素,那么同时更新它们的最优雅方式是什么?



例如:

 < head> 
< title id =pageTitle>我的应用程式< / title>
< / head>
< body>
< h1 id =screenTitle>我的应用程式< / h1>
< / body>

我希望screenTitle和pageTitle的innerHTML在JavaScript函数改变其中一个时保持相同。

我知道我可以遍历pageTitle和screenTitle元素,每当更改字符串我的应用程序时都更新它们,但是有没有更优雅的方式? / p>

解决方案

document.title.innerHTML 在IE中是只读的。这应该是一个跨浏览器的方法:

  document.getElementById('screenTitle')。innerHTML = document.title ='我的应用程序'; 

而不是文字值,您可以使用一个变量ofcourse。



如果您确实需要优雅(===异国情调),您可以使用 setter

  var page = {
set title (text){
document.getElementById('screenTitle')。innerHTML = document.title = text;
}
};

当您需要更改标题时,只需设置它:页。 title = newTitle; 。只有你需要关心,是你可以从当前范围引用 page 对象。此外,这只适用于现代浏览器。


If I have two HTML elements that should always contain the same inner HTML text, what is the most elegant way to update them both at the same time?

For example:

<head>
    <title id="pageTitle">My Application</title>
</head>
<body>
    <h1 id="screenTitle">My Application</h1>
</body>

I would like the innerHTML of screenTitle and pageTitle to remain identical whenever a JavaScript function changes one of them.

I know I can iterate through the pageTitle and screenTitle elements, updating each of them whenever I change the string "My Application", but is there a more elegant way?

解决方案

document.title.innerHTML is read-only in IE. This supposed to be a cross-browser method:

document.getElementById('screenTitle').innerHTML = document.title = 'My Application';

Instead of a literal value you can use a variable ofcourse.

If you really need something "elegant" (=== exotic), you can use a setter:

var page = {
    set title(text) {
        document.getElementById('screenTitle').innerHTML = document.title = text;
    }
};

When ever you need to change the titles, just set it: page.title = newTitle;. Only you need to care of, is that you can refer page object from the current scope. Also this will only work in modern browsers.

这篇关于一个HTML元素镜像的另一个最优雅的方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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