简体   繁体   English

单击页面上的按钮时如何使用原生 js 应用 css

[英]How to apply css with native js when a button is clicked on the page

I want to apply a style when clicking a button on the page.我想在单击页面上的按钮时应用样式。 The button has a data-selector attribute.该按钮具有数据选择器属性。 This attribute is the selector where I want to apply the css.此属性是我要应用 css 的选择器。

HTML example: HTML 示例:

<ul>
<li><button class="button" data-selector="#skip > p > a">Button 1</button></li>
<li><button class="button" data-selector="#menu > div" >Button 2</button></li>
<li><button class="button" data-selector="#social">Button 3</button></li>
</ul>

<div id=#menu>
<div id="skip">
<p><a href="/pages">Hello</a></p>
</div>

<div id=social>
<p>Example 1</p>
<p>Example 2</p>
</div>
</div>

  <script type="text/javascript">
var error = document.querySelectorAll(".button");
    for (var i=0;i<error.length;i++){
        error[i].addEventListener("click", function() {
            var selector = error[i].getAttribute('data-selector');
            selector.style.border = '2px solid red';
        }, false);
    }
</script>

Result: error[i] is undefined结果: error[i] 未定义

I'm using js native because I can not use jQuery我使用 js native 因为我不能使用 jQuery

PS:Sorry for my bad english PS:对不起,我的英语不好

Two errors.两个错误。 First, you are getting the selector string but never actually the DOM element that it represents.首先,您获得的是选择器字符串,但实际上从未获得它所代表的 DOM 元素。 Second, you need to use this within the function context.其次,您需要在函数上下文中使用this Working code:工作代码:

 var error = document.querySelectorAll(".button");
 for (var i=0;i<error.length;i++){
    error[i].addEventListener("click", function() {
        var selector = this.getAttribute('data-selector');
        document.querySelectorAll(selector)[0].style.border = '2px solid red';
    }, false);
}

jsfiddle: https://jsfiddle.net/h5eqg4tp/ jsfiddle: https://jsfiddle.net/h5eqg4tp/

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

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