如何使用jQuery选择以特定字符开头的ID元素?

给定一个HTML文档,如何使用jQuery选择ID以特定字符开头的元素?下面本篇文章就来给大家介绍一下使用jQuery选择以特定字符开头的ID的方法,希望对大家有所帮助。

想要使用jQuery选择ID以特定字符开头的元素,可以使用jquery的[attribute^=value]选择器来实现。[attribute^=value] 选择器选取每个带有指定属性且以指定字符串开头的元素。

语法:

$("[attribute^='value']")

下面通过示例来看看[attribute^=value]选择器的使用。

示例:选择id以“demo”开头的元素并更改其背景颜色

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<style> 
            #demo_div { 
                background: green; 
                height: 100px; 
                width: 200px; 
                margin: 0 auto; 
                color: white; 
                line-height: 100px;
            } 
        </style> 
          
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script> 
    </head>  
      
    <body style = "text-align:center;">  
        <div id = "demo_div"> 这是div盒。</div> 
        <p id = "demo_p" style ="font-size: 19px; font-weight: bold;"></p> 
        <button onClick = "GFG_Fun()">点击这里</button> 
          
        <p id = "demo_DOWN" style = "color: white; font-size: 24px; font-weight: bold;"> </p> 
          
        <script> 
            $('#demo_p').text("点击按钮,选择id以“demo”开头的元素并更改背景色。"); 
            function GFG_Fun() { 
                $( "[id^='demo']" ).css("background-color", "pink"); 
                $('#demo_DOWN').text("测试文字!");
            } 
        </script>  
    </body>  
</html>

输出:

1.gif

以上就是如何使用jQuery选择以特定字符开头的ID元素?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » jQuery 答疑