显示变量列表中的文本 [英] Display text from list of variables
问题描述
我的网站上有一系列页面,这些页面利用JavaScript根据页面中定义的变量显示标题.
I have a series of pages on my site that utilize JavaScript to show a title based on the variable defined in the page.
基本HTML
<h1 id="pageTitle"></h1>
<script> var page = "start";</script>
<!-- Rest of the page... -->
单独的JavaScript文件
Separate JavaScript File
var startText = "Hello!";
var middleText = "This is a page";
var endText = "Example";
if(page == 'start'){
$('#pageTitle').html(startText);
}
if(page == 'middle'){
$('#pageTitle').html(middleText);
}
if(page == 'end'){
$('#pageTitle').html(endText);
}
这遵循一种简单的模式,可以很好地完成工作,但是随着网站的发展可能会变得乏味.有没有更干净的方法来获得相同的结果?
This follows a simple pattern that does the job fine, but can get tedious as the website grows. Is there a cleaner way to get the same result?
推荐答案
我建议不要在每个页面中定义JS变量,而是将data-*
属性附加到title标签,例如:
Instead of defining a JS variable in every page I suggest to attach a data-*
attribute to the title tag like :
<h1 id="pageTitle" data-page="start"></h1>
然后在单独的JS文件中,您可以创建一个包含title
列表的对象,并使用data-page
属性作为键,例如:
Then in your separate JS file, you could create an object contains the list of title
and use the data-page
attributes as a key like :
var titles = {
"start": "Hello!",
"middle": "This is a page",
"end": "Example"
}
var title_element = $("#pageTitle");
var key = title_element.data('page');
title_element.text(titles[key]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="pageTitle" data-page="middle"></h1>
这篇关于显示变量列表中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!