简体   繁体   English

如何将样式添加到单击另一个按钮时创建的按钮?

[英]How to add styles to a button that is created when clicking another button?

I have this button that is loaded whenever u click another button(so its not loaded on startup without me doing anything) 每当你点击另一个按钮时,我都会加载这个按钮(所以在没有我做任何事情的情况下它没有在启动时加载)

<button type='button' id='testbtn' 
onclick='testfunction()' onload='testload()' 
class='testbtnclass'>btn</button>

This is my function: 这是我的功能:

 function testload() {

alert("onload worked");
 /*what i want to archieve within this function later is to change the
 css of the button but for now i just want to call this function onload of 
 the button, which it doesnt/*
}

My question is now, how can i/should i do to get this function to run whenever this button is loaded? 我现在的问题是,如果加载此按钮,我该怎么做才能让这个函数运行?

I believe you can create a css class example: 我相信你可以创建一个css类示例:

.buttonStyle{ background-color: red };

Then you can get your button and add this class 然后你可以得到你的按钮并添加这个课程

var button = document.getElementById("testbtn");
button.className = button.className + " buttonStyle";

onload is not supported by button tag so you need to do it either as other answer telling or with button标记不支持onload ,因此您需要将其作为其他答案告诉或使用

document.onload =function(){

  //change the css of that button or call function you want 

}

使用jQuery,您可以执行以下操作:

$( "button" ).addClass( "myClass yourClass" );

You could use event delegation of jQuery. 您可以使用jQuery的事件委托。 With this technique, it doesnt matter if the button gets generated after DOM is loaded. 使用这种技术,如果在加载DOM后生成按钮无关紧要。

$('body').on('click', '.generated_btn', function() {
    //here you can change css
});

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. 事件委托允许我们将单个事件侦听器附加到父元素,该元素将为匹配选择器的所有后代触发,无论这些后代现在是存在还是将来添加。

More information: https://learn.jquery.com/events/event-delegation/ 更多信息: https//learn.jquery.com/events/event-delegation/

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

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