基本的 InnerHTML 问题
这是我在循环中使用的一段代码,用于将 HTML 元素附加到 Google Chrome 扩展程序的 popup(.html):
- “wordlist”是一个单词数组。
- 'rand' 是随机数生成函数。
代码:
for (l=1; l<11; l++) {
var i = rand(wordlist.length;
var h1 = document.createElement("h1");
h1.innerHTML = wordlist[i];
document.body.appendChild(h1);
}
没有预先存在的 HTML 元素。因此,此代码将 10 个随机单词附加到空白页。
现在,我想将链接附加到页面,而不是附加到页面的单词(例如:http://dictionary.reference.com/browse/**wordlist[i]**
,这基本上是该特定单词的 Dictionary.com 查询)。另外,我希望在
PS:我前一天开始学习 HTML 和 JS,我太兴奋了,无法开始编写一些代码。如果我忽略了一个简单的 Google 解决方案来解决我的问题,我深表歉意。感谢您抽出时间。
this is the piece of code that I am using in a loop to append an HTML element to a Google Chrome Extension's popup(.html):
- 'wordlist' is an array of words.
- 'rand' is the Random number generating function.
Code:
for (l=1; l<11; l++) {
var i = rand(wordlist.length;
var h1 = document.createElement("h1");
h1.innerHTML = wordlist[i];
document.body.appendChild(h1);
}
There are no pre-existing HTML elements. So, this code is appending 10 random words to a blank page.
Now, instead of the words being appended to the page, I want to append links to the page (eg: http://dictionary.reference.com/browse/**wordlist[i]**
, which is basically a dictionary.com query for that particular word). Also, I want this link to be opened in a new Chrome tab when clicked. How do I do this?
P.S: I started learning HTML and JS a day before, and I was too excited to start writing some code. I apologize if I have overlooked a simple Google solution to my problem. Thank you for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
基本上只需将 h1 更改为 a 即可。
还要设置属性 href(链接)和 target(应为 openend)。
Basicly just change h1 to a.
Also set the attribute href (the link) and target (where it should be openend).
如果您想使用 DOM,
下面的代码会更快,因为您只需附加 HTML 一次(并且 DOM 操作的成本很高):
If you want to work with the DOM,
The following will be faster, since you'll append the HTML only once (and DOM operations are costly):
尝试将代码更改为以下内容:
我修复了第 2 行中的问题,您省略了右括号。
我还更明显地将你的 h1 更改为 a,并添加了一行设置其 href 的行。
Try changing your code to the following:
I fixed a problem in line 2, you'd omitted a closing parenthesis.
I also more obviously changed your h1 to an a, and added a line that sets its href.
嗯,它就像更改
为您想要的一样简单,即:
要使其在新选项卡中打开,您必须添加属性“目标”并为其指定空白值。我认为它在 HTML 5 中已被弃用......
Well its as easy as changing
to exatly what you are after, namely:
To make it open in a new tab you have to add the attribute "target" and give it a value of blank. I think its deprecated in HTML 5 though...