问题描述
所以我有 1 个以上的 html 文件,在每个文件中都有一个像
的元素,id:'level1' 所以 ```
在我拥有的 js 文件上:
var level1 = {
name: 'Hello',author: 'me',id: '1'
}
然后我用innerText在html页面上写这些信息,但我也尝试了innerHTML和TextContent
document.getElementById('level1').innerText = level1.name;
以及所有其他名称,但我在所有文件中只看到第一个 var 信息,但我还有其他 var,例如 level2 level3,它们以相同的方式打印,但其他变量仅显示在一个 html 文件中>
在我的代码中:
index.html
<!-- #1 -->
<div class="table">
<a href=""><img class="thumb" onclick="video1x1()" src="images/img1.jpg" width="16%" height="80%"></a>
<a href="list/1"><p class="p1" id="level1"></p></a>
<p class="author" id="author1"></p>
</div>
<!----->
1.html
<p class="title" id="level1"></p><a href="../2"><p class="ttitle">></p>
这对 level1 var idk 有效,但对其他人没有。
基本上我希望它在每个具有 id="level1" 的元素上写成 level1.name
解决方法
使用当前的 javascript 变量格式,为正确的元素轻松选择正确的值有点麻烦 - 但您可以执行以下操作:
var level1 = {
name: 'Hello',author: 'me',id:1
}
var level2 = {
name: 'Goodbye',author: 'you',id:2
}
// find all the elements that have an ID beginning with "level"
document.querySelectorAll('[id^="level"]').forEach( ( el,i )=>{
// to refer to the numbered variable define it as a property of the window
let obj=window[ 'level'+( i + 1 ) ];
if( obj ){
// find the number from the HTML element
let a=el.id.match(/\d/);
// if the current HTML element index (+1) matches the number above....
if( a==(i + 1) ){
// change the content of the element
el.innerHTML=obj.name;
el.parentNode.parentNode.querySelector( 'p.author' ).innerHTML=obj.author;
}
}
});
<div class="table">
<a href=""><img class="thumb" onclick="video1x1()" src="images/img1.jpg" width="16%" height="80%"></a>
<a href="list/1"><p class="p1" id="level1"></p></a>
<p class="author" id="author1"></p>
</div>
<div class="table">
<a href=""><img class="thumb" onclick="video1x1()" src="images/img2.jpg" width="16%" height="80%"></a>
<a href="list/2"><p class="p2" id="level2"></p></a>
<p class="author" id="author2"></p>
</div>
如果将 JS 变量压缩为单个变量会更容易,而 JSON 将是一个很好的候选者。这将使匹配代码更简单、更健壮。
即:
var levels={
1:{name:'Hello',author:'me'},2:{name:'Goodbye',author:'you'}
};
诚然,上述内容不是有效的 JSON - 它是一个对象文字,但您明白了。如果您在幕后最初使用它来创建变量,则很容易从数据库生成此类内容
var levels={
1:{name:'Hello',author:'you'}
};
Object.keys( levels ).forEach( i=>{
let obj=levels[ i ];
let name=document.querySelector('[id="level'+i+'"]');
let author=document.querySelector('[id="author'+i+'"]');
if( name )name.innerHTML=obj.name;
if( author )author.innerHTML=obj.author;
})
<div class="table">
<a href=""><img class="thumb" onclick="video1x1()" src="images/img1.jpg" width="16%" height="80%"></a>
<a href="list/1"><p class="p1" id="level1"></p></a>
<p class="author" id="author1"></p>
</div>
<div class="table">
<a href=""><img class="thumb" onclick="video1x1()" src="images/img2.jpg" width="16%" height="80%"></a>
<a href="list/2"><p class="p2" id="level2"></p></a>
<p class="author" id="author2"></p>
</div>