简体   繁体   English

是否可以使用setAttribute设置超链接的文本或innerText

[英]Is it possible to set the text or innerText of a hyper link using `setAttribute`

I'm trying to dynamically convert my descriptive JSON object into HTML. 我试图将我的描述性JSON对象动态转换为HTML。 This is no easy task but since it's only to be used for a small project and a small team, it suits our needs. 这不是一件容易的事,但是因为它仅用于一个小型项目和一个小型团队,所以它满足了我们的需求。

This means, the JSON object could look like 这意味着JSON对象可能看起来像

'element': {
            'href': '#03',
            'text': 'link',
            'myUniqueTag' : 'a'
        }

This means I can use myUniqueTag and understand I'm dealing the type a . 这意味着我可以使用myUniqueTag并了解我正在处理a类型。 This works fine. 这很好。

The issue I have is setting the value of the text, which is 我遇到的问题是设置文本的值,即

<a href="blah">How do I set this bit</a>

This is what I've tried 这就是我尝试过的

one.text = "Hello world";                           //works
two.innerText = "Hello world";                      //works
three.setAttribute("text", "Hello world");          //fails
four.setAttribute("innerText", "Hello world");      //fails

JSFIDDLE JSFIDDLE

For my situation, I have to use setAttributes. 对于我的情况,我必须使用setAttributes。 My question is, am I missing something or is it not possible to set the text via setAttribute() 我的问题是,我丢失了什么东西还是无法通过setAttribute()设置文本

Please note, I'm using vanilla JavaScript only (no JQuery or framework). 请注意,我仅使用普通JavaScript(没有JQuery或框架)。

Of course you can use setAttribute to set the text, however you need to precise witch attribute you set. 当然,您可以使用setAttribute设置文本,但是您需要精确设置所设置的witch属性。 In your example "text" and "innerText" are not html attribute. 在您的示例中,“ text”和“ innerText”不是html属性。

for example : 例如 :

JS: JS:

var b = document.createElement('button'); 
b.setAttribute('content', 'test content'); 
b.setAttribute('class', 'btn'); 
b.innerHTML = 'test value';

var wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);

Looks like this in the DOM: 在DOM中看起来像这样:

<div id="divWrapper">
    <button content="test content" class="btn">test value</button>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM