简体   繁体   English

如何判断我的元素是否需要innerHTML或值

[英]How to tell whether my element needs innerHTML or value

I am using JavaScript to run some AB tests on my site. 我正在使用JavaScript在我的网站上运行一些AB测试。 I am able to change the text in my <button> 's with element.innerHTML = "Text that I want" but using that same strategy I cannot change the text in <input type="submit"> 's. 我可以使用element.innerHTML = "Text that I want"来更改<button>element.innerHTML = "Text that I want"但是使用相同的策略,我无法更改<input type="submit">的文本。

Inversely, I can change the value of submit buttons using element.value = "Text that I want" , but cannot change a <button> 's text in that way. 相反,我可以使用element.value = "Text that I want"来更改提交按钮的值,但是不能以这种方式更改<button>的文本。

So my question is, how can I know which function needs to be used on a specific element so that I can create an algorithm that handles every type of element? 所以我的问题是,我如何才能知道需要在特定元素上使用哪个函数,以便创建可以处理每种类型元素的算法?

In short: How do I know whether to use element.innerHTML or element.value programmatically? 简而言之:如何知道以编程方式使用element.innerHTML还是element.value

NOTE: jQuery is not allowed. 注意:不允许使用jQuery。

Example - Here is some code that takes a class name as input and changes the element throughout the page. 示例-这是一些代码,将类名作为输入并在整个页面中更改元素。 Sometimes an <input> may have the identifying class, but sometimes it may be a <div> , <button> or <p> . 有时<input>可能具有识别类,但有时可能是<div><button><p>

var execute = function(experimentName, variation){
        var elements = document.getElementsByClassName(experimentName);
        for (var j = 0; j < elements.length; j++) {
            if (typeof(variation) == "function")
            {
                variation.call(elements[j]);
            }
            else
            {
                elements[j].value = variation;
                //elements[j].innerHTML = variation;
            }
        }
    };

If you are trying to do it in a generic way you could make an instanceof check against the input element's interface class : 如果您尝试以通用方式执行此操作,则可以针对输入元素的接口类进行instanceof检查:

if( element instanceof HTMLInputElement ){
    element.value = "foo";
} else {
    element.innerHTML = "foo";
}

The same way you know how to use that element in HTML in the first place. 首先,您以相同的方式知道如何在HTML中使用该元素。

innerHTML sets the element's contents; innerHTML设置元素的内容; value sets the element's value="" attribute. value设置元素的value=""属性。

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

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