jQuery noConflict()

时间:2020-02-23 14:46:11  来源:igfitidea点击:

jQuery noConflict()方法释放$变量的控件。
您可能已经看到许多使用$变量JavaScript库。
在jQuery中,$用作jQuery别名。
如果您想使用其他库的$变量,则jQuery必须通过调用noconflict方法来释放对$变量的控制。

jQuery noConflict

这是使用jQuery noConflict方法的常规语法:

$.noConflict()
<!-- OR --> 
jQuery.noConflict()

jQuery noConflict示例

以下示例演示了jQuery noConflict方法的用法。

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$.noConflict();
$(document).ready(function(){
$("button").click(function(){
  $("div").fadeToggle("slow"); //This won’t work
});
});
</script>
<style>
.divBlock{
width: 100px;
height: 50px;

padding: 15px;
margin: 15px;
background-color: red;
}
</style>
</head>

<body>

<div class="divBlock"></div>
<button>Test</button>

</body>
</html>

在上面的示例中,淡化和切换效果应用于<div>元素。

您将无法获得所需的输出,因为它在$(document).ready()函数上方使用了$.noConflict()方法。
如果删除$.noConflict()方法,则上面的代码将为您提供适当的结果。

在下面的示例中,您可以看到在就绪函数和所有其他方法中使用了$.noconflict()并使用了全名jQuery,而不是$变量。
即使使用noConflict()方法,该代码也可以使用。

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$.noConflict();
jQuery(document).ready(function(){
jQuery("button").click(function(){
  jQuery("div").fadeToggle("slow"); //This is working
});
});
</script>
<style>
.divBlock{
width: 100px;
height: 50px;

padding: 15px;
margin: 15px;
background-color: red;
}
</style>
</head>

<body>

<div class="divBlock"></div>
<button>Test</button>

</body>
</html>

jQuery noConflict别名

在下面的示例中,您可以看到$.noConflict()方法与自定义别名" jq"一起使用。
此代码还将为您提供正确的输出。

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
jq = $.noConflict();
jq (document).ready(function(){
jq ("button").click(function(){
  jq ("div").fadeToggle("slow"); //this is still working
});
});
</script>
<style>
.divBlock{
width: 100px;
height: 50px;

padding: 15px;
margin: 15px;
background-color: red;
}
</style>
</head>

<body>

<div class="divBlock"></div>
<button>Test</button>

</body>
</html>

jQuery使用noConflict()方法来避免$变量与其他JavaScript变量的冲突。