链接前的JavaScript插入按钮,而不是之后

时间:2013-11-23 21:34:25

标签: javascript css

我有以下代码示例,我在页面加载后插入一个按钮,我希望该按钮进入该div内部,但在该链接之后它是可信的(link to jsFiddle)?

HTML

<div class="someclass" id="someid">
    <a href="#" class="">Text Here</a>
</div>

的JavaScript

(function(root) {
    function bindUIActions() {
        menuElements();
    }
    function menuElements() {
        var menuElements = document.getElementById("someid");
        menuElements.insertAdjacentHTML('afterBegin','<button type="menu-button" id="responsiveToggle" class="menu-button" aria-hidden="true"><i aria-hidden="true" class="icon-reorder"></i>Menu</button>');
    }
    root.NavigationWidget = {
        init: function() {
            bindUIActions();
        }
    };

})(this);
NavigationWidget.init();

2 个答案:

答案 0 :(得分:2)

似乎有很多代码,但更合适的方法是:

var menuElements = document.getElementById("someid"),
    button       = document.createElement('button'),
    i            = document.createElement('i'),
    txt          = document.createTextNode('Menu');

button.type      = 'button';
button.id        = 'responsiveToggle';
button.className = 'menu-button';

i.className      = 'icon-reorder';

button.setAttribute('aria-hidden', 'true');
i.setAttribute('aria-hidden', 'true');

button.appendChild(i);
button.appendChild(txt);
menuElements.appendChild(button);

FIDDLE

答案 1 :(得分:1)

使用&#39; beforeend&#39;

menuElements.insertAdjacentHTML('beforeend','<button type="menu-button" id="responsiveToggle" class="menu-button" aria-hidden="true"><i aria-hidden="true" class="icon-reorder"></i>Menu</button>');

https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML