jQuery添加CSS,添加html元素
时间:2020-02-23 14:46:03 来源:igfitidea点击:
jQuery add方法可用于将元素,选择器或者html添加到匹配的元素。
jQuery add()
如果您想应用任何jQuery函数或者将CSS添加到HTML中的DOM元素,则jQuery add()方法非常有用。
下面的示例显示了如何使用add()将CSS样式应用于" table"," p"和" li" DOM元素。
否则,我们必须在每个元素上一一应用样式。
它还显示了如何将HTML添加到任何DOM元素。
<html> <head> <script type="text/javascript" src="jquery-1.8.3.min.js"></script> <style type="text/css"> .styled{ border:1px black solid; background-color: read; border-collapse: collapse; } </style> <script type="text/javascript"> function styleToggle(button) { if (button.value == 'Add Style') { //using add() we can apply css to all the elements at once $('table').add('p').addClass('styled').add('li').css('background-color', 'red'); button.value = 'Remove Style'; } else { //using removeAttr() to remove the styling $('table').add('p').add('li').removeClass('styled').removeAttr('style'); button.value = 'Add Style'; } $().add("<br>appending html").appendTo("p:last"); } </script> <title>jQuery add() Example</title> </head> <body> Employee Table <br> <table> <tbody> <tr> <th>ID</th> <th>NAME</th> <th>ROLE</th> </tr> <tr> <td>1</td> <td>hyman</td> <td>Developer</td> </tr> <tr> <td>2</td> <td>Mike</td> <td>Manager</td> </tr> <tr> <td>3</td> <td>David</td> <td>CEO</td> </tr> <tr> <td>4</td> <td>Lisa</td> <td>Support</td> </tr> </tbody> </table> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> </ul> <p>A Paragraph</p> <p>Last Paragraph</p> <br> <input type="button" value="Add Style" onclick="styleToggle(this)"></input> </body> </html>