介绍jQuery中的美元符号符号冲突。
在 jQuery 中,$ 符号是 jQuery 的简写形式,它是 jQuery 函数的别名。
// 两种写法等价
$("#test").hide();
jQuery("#test").hide();
$("p"); // 选择所有 p 元素
$(".test"); // 选择所有 class="test" 的元素
$("#test"); // 选择 id="test" 的元素
$("<p>新段落</p>");
$(function(){
// 文档就绪后执行
});
当多个 JavaScript 库都使用 $ 符号时,就会产生冲突。
// Prototype 也使用 $ 符号
var $ = function(id) {
return document.getElementById(id);
};
// jQuery 也使用 $ 符号
$("#test").hide(); // 冲突!
$.noConflict();
// 使用 jQuery 代替 $
jQuery("#test").hide();
var jq = $.noConflict();
jq("#test").hide();
$.noConflict();
jQuery(document).ready(function($){
$("#test").hide(); // 在函数内部可以使用 $
});
$.noConflict();
(function($){
$(function(){
$("#test").hide();
});
})(jQuery);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery $ 符号示例</title>
<style>
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: Arial, sans-serif;
}
.demo-section {
margin-bottom: 30px;
padding: 20px;
background-color: #f8f9fa;
border-radius: 8px;
}
.box {
width: 200px;
height: 200px;
background-color: #3498db;
color: white;
text-align: center;
line-height: 200px;
border-radius: 8px;
margin: 10px auto;
}
button {
padding: 10px 20px;
margin: 5px;
background-color: #3498db;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #2980b9;
}
.code-block {
background-color: #2c3e50;
color: #ecf0f1;
padding: 15px;
border-radius: 5px;
font-family: 'Courier New', monospace;
font-size: 14px;
overflow-x: auto;
}
</style>
</head>
<body>
<div class="container">
<h1>jQuery $ 符号</h1>
<div class="demo-section">
<h3>$ 符号用法</h3>
<div class="code-block">
$符号的作用:<br>
1. 选择元素:$("p")<br>
2. 创建元素:$("<p>新段落</p>")<br>
3. 执行函数:$(function(){})
</div>
</div>
<div class="demo-section">
<h3>功能测试</h3>
<div class="box" id="testBox">测试盒子</div>
<button onclick="testDollar()">使用 $ 符号</button>
<button onclick="testjQuery()">使用 jQuery</button>
<button onclick="testNoConflict()">测试 noConflict</button>
<button onclick="resetBox()">重置</button>
</div>
</div>
<script>
function testDollar() {
$("#testBox").fadeOut(500).fadeIn(500);
}
function testjQuery() {
jQuery("#testBox").slideUp(500).slideDown(500);
}
function testNoConflict() {
var jq = $.noConflict();
jq("#testBox").css("background-color", "#e74c3c").text("noConflict").delay(1000).queue(function(next){
jq(this).css("background-color", "#3498db").text("测试盒子");
next();
});
// 恢复 $ 符号
$ = jQuery;
}
function resetBox() {
$("#testBox").css("background-color", "#3498db").text("测试盒子").show();
}
</script>
</body>
</html>
$ 符号是 jQuery 的核心,理解其用法和冲突解决方法非常重要: