JQUERY Click()方法调用 外部函数

本文介绍了JQUERY中click方法调用外部函数的两种方式,通过示例代码展示了错误的直接调用方式和正确的匿名函数包裹调用方式。重点在于理解事件处理函数的执行时机。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
<head>
	<title>Second</title>
	<script type="text/javascript" src = "https://code.jquery.com/jquery-3.3.1.js"></script>
	<script type="text/javascript">
		
		var xhr;

		function createXmalHRequest(){

			if(window.ActiveXObject){
				return new ActiveXObject("Microsoft.XMLHTTP");
			}
			else if(window.XMLHttpRequest){
				return new XMLHttpRequest;
			}
		}

		function handleStateChange(){

			if(xhr.readyState == 4){
				if(xhr.status == 200){
					alert("the change is"+xhr.responseText);
					$(document).ready(function(){
						$("p.a").html(xhr.responseText);
					})
				}
			}
		}

		function startAjax(){

			xhr = createXmalHRequest();
			xhr.open("GET","gagaga.txt",true);
			xhr.onreadystatechange = handleStateChange;
			xhr.send(null);

		}
		
		$(function(){
			$("p.b").click(function(){testAjax()});
		});

		function testAjax(){
				var xhr1 = new XMLHttpRequest();
			console.log(xhr1.readyState);
			xhr1.open("GET","abc.txt",true);
			xhr1.onload = function(){
				$("p.b").html(xhr1.responseText);
			}
			xhr1.send(null);
			};

		
		 
   
	</script>
</head>
<body>


<input type="button" name="btn1" value="onClick" onclick="startAjax()">
<p class="a">ddfddddd</p>
<p class="b">Hello Pb</p>
</body>
</html>

 

 

    $(function(){
            $("p.b").click(testAjax());
        });

        function testAjax(){
                var xhr1 = new XMLHttpRequest();
            console.log(xhr1.readyState);
            xhr1.open("GET","abc.txt",true);
            xhr1.onload = function(){
                $("p.b").html(xhr1.responseText);
            }
            xhr1.send(null);
            };

 

 

这样写不对

        $(function(){
            $("p.b").click(function(){testAjax()});
        });
这样写才可以。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值