jquery和js操作属性

本文详细介绍了如何使用HTML和JS设置元素的属性,包括使用attr()方法和setAttribute()方法,展示了两种方法的差异,并提供了实例演示。

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

<p>1234</p>
<img src="../images/logo.jpg" alt="welcome" />
<script type="text/javascript">
	$(function(){
		/*-----------jquery使用attr()方法设置属性-----------------*/
		$("p").attr("title","this is title");
		
		//jquery的attr()方法可以批量设置属性
		$("img").attr({"src":"images/banner.jpg", "title":"this is image"});
		
		//如果只有一个参数的话就是获取
		var $_title = $("img").attr("title");
		alert($_title);
		
		//jquery删除属性用removeAttr()方法
		$("p").removeAttr("title");
	});
	
	window.onload= function(){
		/*-----------------js使用setAttribute()方法设置属性----------------*/
		//js的setAttribute()方法不能批量设置属性
		var p = document.getElementsByTagName("p")[0];
		p.setAttribute("title","this is js title");
		
		//js获取属性的方法是getAttribute()
		p.getAttribute("title");
		
		//js删除属性的方法是removeAttribute()
		document.getElementsByTagName("p")[0].removeAttribute("title");
		
	}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值