tips:Jquery的attr和prop的区别

Jquery的attr和prop的区别


描述:想做一个复选框checkbox全选的功能,当勾选全选后,将子项的复选框状态设置成一致的,


但遇到了一个问题,就是attr函数并不能改变子项的checkbox的状态,而换成prop函数就可以了。


原因在于attr和prop的区别:我觉得有句话概括的非常好

---------对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。

---------对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。

----------------来自〖芈老头〗的技术空间-All For Better Codes


就拿我的代码做例子:

jsp:

<th>
<label class="am-checkbox"> <input type="checkbox" id="selectAll" data-am-ucheck> 全选 </label>
</th>

<c:forEach items="${pb.beanList }" var="product">
<tr class="even gradeC">

<td>
<label class="am-checkbox"> <input type="checkbox" value="${product.productId }" name="checkboxBtn" data-am-ucheck> </label>
</td>

</tr>
</c:forEach>

js:

$(function() {

	/*
	 * 给全选添加click事件
	 */
	$("#selectAll").click(function() {
		/*
		 * 1. 获取全选的状态
		 */
		var bool = $("#selectAll").prop("checked");
		/*
		 * 2. 让所有条目的复选框与全选的状态同步
		 */
		setItemCheckBox(bool);

	});

});

/*
 * 统一设置所有条目的复选按钮
 */
function setItemCheckBox(bool) {
	$(":checkbox[name=checkboxBtn]").prop("checked", bool);
}

checkbox选中属性对应“checked”,属于固有属性,因此需要使用prop方法去操作才能获得正确的结果,如果用attr则会出现undefined这样的错误。


所以说,要分清属性的情况再选择用prop还是attr。用错的话就会出现undefined这样的错误。

{extend name="public/base" /} {block name="body"} <link href="/public/plugs/datepicker/css/foundation-datepicker.min.css" rel="stylesheet" type="text/css"> <script src="/public/plugs/datepicker/js/foundation-datepicker.js"></script> <script src="/public/plugs/datepicker/js/foundation-datepicker.zh-CN.js"></script> <script type="text/javascript" src="__PUBLIC__/js_manage/account_manage.js"></script> <link rel="stylesheet" href="/application/user/static/css/chat.css" type="text/css"/> <link href="/public/css/callrecord.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src='/public/js/paging.js'></script> <script type="text/javascript" src='/public/js_validation/validation.js'></script> <link href="/public/css/intentionnal_member2.css" rel="stylesheet" type="text/css"/> <div class="row"> <div class="col-lg-12"> <div class=" clearfix fadeInRight animated"> <div class=" main-box"> <header class="main-box-header clearfix callrecord-title"> <div class="pull-left"> <span class="n_panel_title"><img src="__PUBLIC__/img/e_yixiang.png" alt="">客户管理</span> </div> </header> <div class="l_loadfixed" style="display: none;"> <div class="l_loaddata"> <p><img src="/public/img_sj/reload.gif" alt="">正在查询中...</p> <p>由于您的数据过大,加载需要一些时间,我们在努力的加载中...</p> </div> </div> </div> <div class="container-fluid callrecord-bg"> <div class="condition pz_manping_height "> <div class="condition-title"> <img src="__PUBLIC__/img/tiaojianshaixuan.png"> <span>条件筛选</span> <div class="pull-right"> <input type="text" class="form-control c_seachbgimg" id="phone_query" placeholder="请输入号码查询" /> </div> </div> <div class="condition-content"> <div class="form-inline"> <div class="form-group"> <label class="levelSelect">客户姓名:</label> <input type="text" name="" id="name_query" class="form-control width160 marginr30 " value="" placeholder="请输入客户名称"> </div> <div class="form-group"> <label class="levelSelect ">所属坐席:</label> <select class="form-control width160 marginr30" name="" id="sitchair"> <option value="">全部坐席</option> {volist name="seats" id="seat"} <option value="{$seat.id}">{$seat.username}</option> {/volist} </select> </div> <div class="form-group"> <label class="levelSelect ">所属任务:</label> <select class="form-control width160 marginr30" name="" id="config_id"> <option value="">全部任务</option> {volist name="crm_push_config" id="config"} <option value="{$config.id}">{$config.task_name}</option> {/volist} </select> </div> <div class="form-group"> <label class="levelSelect ">创建时间:</label> <input type="text" name="" class="form-control width160 c_datebgimg " id="startCreateDate" value="" placeholder="开始时间"> <script> $('#startCreateDate').fdatepicker({ format: 'yyyy-mm-dd hh:ii', pickTime: true }); </script> <span class="word marginB4">至</span> <input type="text" name="" class="form-control width160 c_datebgimg" id="endCreateDate" value="" placeholder="结束时间"> <script> $('#endCreateDate').fdatepicker({ format: 'yyyy-mm-dd hh:ii', pickTime: true }); </script> </div> </div> <!--<div class="form-inline" style="margin-bottom:8px!important;">--> <!-- <div class="form-group">--> <!-- <label class="levelSelect">通话次数:</label>--> <!-- <input type="number" name="" id="min_call_count" class="form-control width58" value="" >--> <!-- <span class="word marginB4">至</span>--> <!-- <input type="number" name="" id="max_call_count" class="form-control width58" value="">--> <!-- <span class="word marginB4">次</span>--> <!-- </div>--> <!--</div>--> <div class="form-inline" style="margin-bottom:8px!important;"> <div class="form-inline intention"> <div class="form-group"> <label class="levelSelect">意向等级:</label> </div> <div class="form-group intention"> <input type="checkbox" name="grade_all" value=""> <label>全部</label> </div> <div class="form-group intention"> <input type="checkbox" name="grade" value="6"> <label>A级意向</label> </div> <div class="form-group intention"> <input type="checkbox" name="grade" value="5"> <label>B级意向</label> </div> <div class="form-group intention"> <input type="checkbox" name="grade" value="4"> <label>C级意向</label> </div> </div> </div> <script> $("input[name='grade_all']").click(function(){ if ($("input[name='grade_all']").is(':checked')) { $("input[name='grade']").prop("checked",true) } else { $("input[name='grade']").prop("checked",false) } }); $("input[name='grade']").click(function(){ if($("input[name='grade']:checked").length==3){ $("input[name='grade_all']").prop("checked",true) }else{ $("input[name='grade_all']").prop("checked",false) } }); </script> <div class="form-inline" style="margin-bottom:8px!important;"> <div class="form-inline intention"> <div class="form-group"> <label class="levelSelect">通话查看:</label> </div> <div class="form-group intention"> <input type="checkbox" name="call_all" value=""> <label>全部</label> </div> <div class="form-group intention"> <input type="checkbox" name="call" value="1"> <label>已查看</label> </div> <div class="form-group intention"> <input type="checkbox" name="call" value="0"> <label>未查看</label> </div> </div> </div> <script> $("input[name='call_all']").click(function(){ if ($("input[name='call_all']").is(':checked')) { $("input[name='call']").prop("checked",true) } else { $("input[name='call']").prop("checked",false) } }); $("input[name='call']").click(function(){ if($("input[name='call']:checked").length==2){ $("input[name='call_all']").prop("checked",true) }else{ $("input[name='call_all']").prop("checked",false) } }); </script> <div class="form-inline" style="margin-bottom:8px!important;"> <div class="form-inline intention"> <div class="form-group"> <label class="levelSelect">客户分配:</label> </div> <div class="form-group intention"> <input type="checkbox" name="distribution_all" value=""> <label>全部</label> </div> <div class="form-group intention"> <input type="checkbox" name="distribution" value="1"> <label>已分配</label> </div> <div class="form-group intention"> <input type="checkbox" name="distribution" value="0"> <label>未分配</label> </div> </div> </div> <script> $("input[name='distribution_all']").click(function(){ if ($("input[name='distribution_all']").is(':checked')) { $("input[name='distribution']").prop("checked",true) } else { $("input[name='distribution']").prop("checked",false) } }); $("input[name='distribution']").click(function(){ if($("input[name='distribution']:checked").length==2){ $("input[name='distribution_all']").prop("checked",true) }else{ $("input[name='distribution_all']").prop("checked",false) } }); </script> <div class="form-inline intention"> <div class="form-group"> <label class="levelSelect">客户意愿:</label> </div> <div class="form-group intention"> <input type="checkbox" name="desire_all" value=""> <label>全部</label> </div> <div class="form-group intention"> <input type="checkbox" name="desire" value="0"> <label>未分类</label> </div> <div class="form-group intention"> <input type="checkbox" name="desire" value="1"> <label>有意向</label> </div> <div class="form-group intention"> <input type="checkbox" name="desire" value="2"> <label>沟通中</label> </div> <div class="form-group intention"> <input type="checkbox" name="desire" value="3"> <label>试用中</label> </div> <div class="form-group intention"> <input type="checkbox" name="desire" value="4"> <label>已成交</label> </div> </div> </div> <script> $("input[name='desire_all']").click(function(){ if ($("input[name='desire_all']").is(':checked')) { $("input[name='desire']").prop("checked",true) } else { $("input[name='desire']").prop("checked",false) } }); $("input[name='desire']").click(function(){ if($("input[name='desire']:checked").length==5){ $("input[name='desire_all']").prop("checked",true) }else{ $("input[name='desire_all']").prop("checked",false) } }); </script> <div class="record-list"> <div class="customer-list clearfix"> <div class="pull-left"> <img src="__PUBLIC__/img/jiluliebiao.png"> <span>客户列表</span> </div> <button type="button" class="btn btn-primary search" onclick="ajax_member();">查询</button> <!--<button type="button" class="btn-primary" onclick="start()">test</button>--> <div class="btn-op pull-right"> <!--<button type="button" class="btn btn-primary btn-operation" onclick="constomerAdd();">添加客户</button> <button type="button" class="btn btn-primary btn-operation" onclick="constomerImport();">导入</button>--> {php}if(config('export_phone_status') == true):{/php} <!--<button type="button" class="btn btn-primary btn-operation" onclick="validation10();">导出</button>--> {php}endif;{/php} {if $role_id neq 20} <button type="button" class="btn btn-primary btn-operation" onclick="constomerAdd();">添加客户</button> <button type="button" class="btn btn-primary btn-operation" onclick="constomerImport();">导入</button> <button type="button" class="btn btn-primary btn-operation" onclick="validation10();">导出</button> <button type="button" class="btn btn-primary btn-operation" onclick="allocationOfSeats();">分配坐席</button> <!-- <button type="button" class="btn btn-primary btn-operation" onclick="newTask();">建任务呼叫</button> --> <button class="btn btn-primary btn-operation" type="button" data-title="建任务呼叫" onclick="addNewPlan(this);" >建任务呼叫</button> <button type="button" class="btn btn-primary btn-operation" onclick="customer_delete_all();">删除</button> {/if} </div> </div> <table class="table table-bordered table-hover"> <thead> <tr> <th class="text-center"> <input class="icheckbox_square-blue" id="member_all_check" type="checkbox" name='all_checked'> </th> <th class="text-center">序号</th> <th class="text-center">姓名</th> <th class="text-center">电话</th> <th class="text-center">所属任务</th> <th class="text-center">意向等级</th> <th class="text-center">客户意愿</th> <th class="text-center">所属坐席</th> <th class="text-center">创建时间 </th> <th class="text-center">最后跟进时间</th> <th class="text-center">操作</th> </tr> </thead> <tbody id="memberlist"> </tbody> </table> <div class="component-page-empty" id="consumeempty"> <div class="empty-tip line"> <p><img src="__PUBLIC__/img/none.png" /></p> <p>暂无数据</p> </div> </div> <footer class="main-box-footer clearfix footerB"> <div class="row"> <div class="col-sm-3 text-left"><input class="check-all all_checked_count" name='DataCheck_all' type="checkbox"/>全选(已选中<span id="user_count">0</span>条客户)</div> <div class="col-sm-9 text-right paging"></div> </div> </footer> </div> </div> </div> </div> </div> </div> <!--添加拨打弹窗--> <div class="modal fade" id="joinShout" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm" style="width:450px; "> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> <span aria-hidden="true">×</span> </button> <h4 class="modal-title" id="myModalLabel"> 添加拨打 </h4> </div> <div class="modal-body l-modal-body" style="padding: 20px 20px 3px;"> <form id="addblacklist-number" method="post" id="addForm" class="form-horizontal margintop" enctype="multipart/form-data" > <div class="form-group"> <label class="col-lg-3 control-label">号码:</label> <div class="col-lg-7 col-sm-7"> <input type="text" class="form-control" name="joinPhone" id="joinPhone" value="" readonly /> </div> </div> <p ></p> <div class="form-group"> <label class="col-lg-3 control-label"><span class="asterisk">*</span>线路:</label> <div class="col-lg-7 col-sm-7"> <select name="line_id" id="line_id" class="form-control"> <option value="">请选择</option> {volist name="line_datas" id="vo"} <option value="{$vo['id']}">{$vo['name']}</option> {/volist} </select> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label"><span class="asterisk">*</span>话术:</label> <div class="col-lg-7 col-sm-7"> <select name="scenarios_id" id="scenarios_id" class="form-control"> <option value="">请选择</option> {volist name="scenarioslist" id="vo"} <option value="{$vo['id']}">{$vo['name']}</option> {/volist} </select> </div> </div> <div class="form-group"> <label class="col-lg-3 control-label"><span class="asterisk">*</span>ASR:</label> <div class="col-lg-7 col-sm-7"> <select name="asr_id" id="asr_id" class="form-control"> <option value="">请选择</option> {volist name="asr_list" id="vo"} <option value="{$vo['id']}">{$vo['name']}</option> {/volist} </select> </div> </div> </form> </div> <div class="modal-footer"> <input type="hidden" id="Nowpagehidden" value=""> <input type="hidden" id="Nowlimithidden" value=""> <button type="button" class="btn btn-default" data-dismiss="modal"> 关闭 </button> <button type="button" class="btn btn-primary" id="users_add" onclick="checkform_dial()" > 确定 </button> </div> </div> </div> </div> <div class="modal fade effect" id="effectTmp" tabindex="1" role="dialog" aria-labelledby="myLargeModalLabel" data-backdrop="static" data-keyboard="false" > <div class="modal-dialog" style="width:365px;"> <div class="modal-content effect-content import"> <div class="modal-header effect-header"> <h4 class="modal-title effect-title" id="singleTel"><span>导入号码</span></h4> </div> <div class="modal-body"> <div class="form-group"> <div class="effect-1"> <span >当前进度</span> <span class="pull-right color90 Progress_value">0%</span> </div> </div> <div class="form-group"> <div class="progress"> <div class="progress-bar progress-bar-data" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"> <span class="sr-only">0%完成</span> </div> </div> </div> </div> <div class="modal-footer effect-footer"> <div>取 消</div> </div> </div> <div class="modal-content effect-content hidden finish"> <div class="modal-header effect-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> <h4 class="modal-title effect-title">导入号码</h4> </div> <div class="modal-body"> <div class="form-group effect-flex"> <i class="effect-success"></i> <div class="effect-success-tip" id="effect-tips-content"> </div> </div> </div> <div class="modal-footer effect-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" id="upload_ok">确定</button> </div> </div> </div> </div> <div class="modal fade effect" id="out_effectTmp" tabindex="1" role="dialog" aria-labelledby="myLargeModalLabel" data-backdrop="static" data-keyboard="false" > <div class="modal-dialog" style="width:365px;"> <div class="modal-content effect-content import"> <div class="modal-header effect-header"> <!--<button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span>--> <!--</button>--> <h4 class="modal-title effect-title" id="singleTel"><span>导出号码</span></h4> </div> <div class="modal-body"> <div class="form-group"> <div class="effect-1"> <span >当前进度</span> <span class="pull-right color90 Progress_value">0%</span> </div> </div> <div class="form-group"> <div class="progress"> <div class="progress-bar progress-bar-data" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"> <span class="sr-only">0%完成</span> </div> </div> </div> </div> <div class="modal-footer effect-footer"> <div>取 消</div> </div> </div> <div class="modal-content effect-content hidden finish"> <div class="modal-header effect-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> <h4 class="modal-title effect-title">导出号码</h4> </div> <div class="modal-body"> <div class="form-group effect-flex"> <i class="effect-success"></i> <div class="effect-success-tip" id="effect-tips-content_outexcel"> </div> </div> </div> <div class="modal-footer effect-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" id="upload_oks">确定</button> </div> </div> </div> </div> <div id="show_validation1"></div> <!-- 页面js引入 --> <script src="__PUBLIC__/js_CRM/intentional_member.js" charset="utf-8"></script> <!-- 页面所有弹框引入 --> <script> $(function(){ $('#start_date').val(getFormatDate(10)); $('#end_date').val(getFormatDate(10)); }) //导出数据 function validation10() { $("#export-data").modal('show'); $('#sel_excel').unbind('click'); $('#sel_excel').on('click', function() { var typez = 10; var arr = []; $("input[name='checkids'][type='checkbox']:checked").each(function(i) { arr[i] = $(this).val(); }); if (arr.length <= 0) { alert('请选择导出的数据'); return false; } else { <?php if($is_verification == 1): ?> $('#export-data').modal('hide'); $('#show_validation1').html(html); $('#export_val').attr('onclick','export_val('+typez+')') $('#export-validation').modal('show'); msm_send(); <?php else: ?> $('#export-data').modal('hide'); constomerExport(); <?php endif; ?> } }) } // 电话脱敏函数 function maskPhone(phone) { return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'); } // 修改 ajax_member 函数,在填充数据时进行脱敏处理 function ajax_member() { // 假设这里是原有的 ajax 请求代码 // $.ajax({ // url: 'your_api_url', // method: 'GET', // success: function(response) { // var memberlist = $('#memberlist'); // memberlist.empty(); // response.forEach(function(item, index) { // var maskedPhone = maskPhone(item.phone); // 对电话进行脱敏处理 // var row = '<tr>' + // '<td class="text-center"><input type="checkbox" name="checkids" value="' + item.id + '"></td>' + // '<td class="text-center">' + (index + 1) + '</td>' + // '<td class="text-center">' + item.name + '</td>' + // '<td class="text-center">' + maskedPhone + '</td>' + // '<td class="text-center">' + item.task_name + '</td>' + // '<td class="text-center">' + item.intention_level + '</td>' + // '<td class="text-center">' + item.customer_wish + '</td>' + // '<td class="text-center">' + item.seat_name + '</td>' + // '<td class="text-center">' + item.create_time + '</td>' + // '<td class="text-center">' + item.last_follow_time + '</td>' + // '<td class="text-center"><button onclick="editMember(' + item.id + ')">编辑</button></td>' + // '</tr>'; // memberlist.append(row); // }); // } // }); } </script> {include file="member/dialog" /} {include file="member/crm_calldetail" /} {include file="public/crm_tageter"/} {include file="public/call_wedget"/} {/block}
06-12
<think>我们正在讨论jQueryattr()prop()方法的区别。根据提供的引用材料,我们可以总结如下: 1. **历史背景**: - `attr()` 方法从jQuery 1.0开始就存在。 - `prop()` 方法是在jQuery 1.6版本中新增的。 2. **基本概念**: - `attr()` 主要用于操作HTML元素的**属性(attributes)**,这些属性是在HTML标签中定义的,例如:`<input type="checkbox" id="test" checked="checked">`中的`type`、`id`、`checked`都是属性。 - `prop()` 主要用于操作DOM元素的**属性(properties)**,这些属性是DOM对象在JavaScript中拥有的属性。 3. **区别**: - 在jQuery 1.6之前,`attr()`方法既用来获取属性(attributes)也用来获取属性(properties)。但在1.6版本之后,为了更清晰地区分,引入了`prop()`方法专门处理DOM属性(properties)。 - 对于某些属性(如`checked`, `selected`, `disabled`等),在jQuery 1.6之后,建议使用`prop()`方法,因为这些属性在DOM元素中表现为布尔值属性(boolean properties),而使用`attr()`可能会得到字符串(例如`"checked"`)或`undefined`,而`prop()`会返回布尔值(`true`或`false`)。 4. **使用建议**: - 对于HTML标签中存在的属性(如`id`, `class`, `style`, `src`等),使用`attr()`。 - 对于DOM元素的布尔值属性(如`checked`, `selected`, `disabled`等),使用`prop()`。 - 对于自定义的HTML属性(非标准属性),使用`attr()`,因为`prop()`可能无法访问。 5. **示例**: - 获取复选框的选中状态: ```javascript // 使用attr()在1.6之前可以,1.6之后不推荐 var isChecked1 = $(':checkbox').attr('checked'); // 返回"checked"或undefined // 使用prop()推荐 var isChecked2 = $(':checkbox').prop('checked'); // 返回true或false ``` - 设置复选框的选中状态: ```javascript // 使用attr() $(':checkbox').attr('checked', true); // 设置checked属性为字符串"checked" // 使用prop() $(':checkbox').prop('checked', true); // 设置DOM的checked属性为布尔值true ``` 6. **引用材料中的关键点**: - 引用[1]指出:在1.6及以后版本,可以根据需要选择使用`attr()`或`prop()`。 - 引用[2]指出:对于`window``document`对象,以及像`checked`这样的属性,应该使用`prop()`代替`attr()`。 - 引用[3]指出:`attr()`可以用于HTMLDOM属性,而`prop()`主要用于DOM属性。 - 引用[4]指出:在jQuery中,attributeproperty是两个不同的概念。 因此,总结如下: - 当操作的是HTML标签上定义的属性(attributes)时,使用`attr()`。 - 当操作的是DOM元素的属性(properties,尤其是布尔值属性)时,使用`prop()`。 这样可以避免在jQuery 1.6及以后版本中出现不一致的行为。 §§相关问题§§ 1. 在jQuery中,如何获取一个复选框的选中状态? 2. 为什么在jQuery 1.6之后,对于`checked`属性推荐使用`prop()`方法? 3. 如何用jQuery设置一个单选按钮(radio)为选中状态? 4. `attr()``prop()`在性能上有什么区别吗? 5. 自定义属性(如`data-*`)应该用`attr()`还是`prop()`访问?</think>### jQuery 中 `attr()` 与 `prop()` 方法的区别详解 在 jQuery 中,`attr()` `prop()` 都用于操作元素属性,但存在关键差异: #### 1. **核心概念区分** - **`attr()`** 操作 **HTML 属性**(定义在 HTML 标签中的属性) 例如:`<input type="checkbox" checked="checked">` 中的 `checked` 属性 返回值为 **字符串**(如 `"checked"` 或 `undefined`) - **`prop()`** 操作 **DOM 属性**(JavaScript 对象的内存属性) 例如:DOM 元素的 `checked` 属性(布尔值) 返回值为 **布尔值**(`true`/`false`)或 **原生数据类型** #### 2. **关键差异对比** | 特性 | `attr()` | `prop()` | |------|----------|----------| | **操作对象** | HTML 标签属性 | DOM 对象属性 | | **返回值类型** | 字符串 | 布尔值/原生类型 | | **适用版本** | jQuery 1.0+ | jQuery 1.6+ | | **动态更新** | ❌ 不随状态变化 | ✅ 实时反映状态 | | **布尔属性** | 返回字符串(如 `"checked"`) | 返回布尔值(`true`/`false`) | #### 3. **典型场景示例** ```javascript // 复选框示例 const $checkbox = $(":checkbox"); // 获取选中状态 $checkbox.attr("checked"); // 返回 "checked" (字符串) $checkbox.prop("checked"); // 返回 true (布尔值) // 设置选中状态 $checkbox.attr("checked", "checked"); // 添加 HTML 属性 $checkbox.prop("checked", true); // 修改 DOM 属性 // 禁用按钮 $("button").attr("disabled", "disabled"); // HTML 方式 $("button").prop("disabled", true); // DOM 方式 ``` #### 4. **使用原则** 1. **布尔属性优先用 `prop()`** `checked`, `selected`, `disabled`, `readonly` 等属性: ```javascript // ✅ 正确做法 if ($(":radio").prop("checked")) { ... } // ❌ 避免 if ($(":radio").attr("checked") === "checked") { ... } ``` 2. **标准 HTML 属性用 `attr()`** `id`, `class`, `src`, `href`, `title` 等: ```javascript // 获取图片路径 const src = $("img").attr("src"); // 添加 CSS 类 $("div").attr("class", "active"); ``` 3. **自定义属性用 `attr()`** `data-*` 等自定义属性: ```javascript // 设置 data-id $("li").attr("data-id", 1001); ``` #### 5. **性能与兼容性** - **性能**:`prop()` 直接操作 DOM 属性,通常比 `attr()` 更快 - **兼容性**: - jQuery 1.5 及之前:只支持 `attr()` - jQuery 1.6+:推荐布尔属性用 `prop()` - **特殊对象**:`window` `document` 的属性操作必须用 `prop()`: ```javascript // 获取视口宽度 $(window).prop("innerWidth"); // 获取文档标题 $(document).prop("title"); ``` #### 6. **为什么需要区分?** HTML 属性与 DOM 属性可能不同步: ```html <input type="checkbox" checked> <!-- 初始状态 --> ``` ```javascript $("input")[0].checked = false; // 通过 JS 修改状态 // 此时: attr("checked") // 仍返回 "checked" (HTML未变) prop("checked") // 返回 false (DOM状态更新) ``` > 总结:**操作布尔属性(`checked`/`selected`/`disabled`)或需要实时状态时用 `prop()`;操作标准 HTML 属性或自定义属性时用 `attr()`**。这是 jQuery 官方推荐的最佳实践[^1][^2][^3][^4]。 --- ### 相关问题 1. 如何用 jQuery 正确获取复选框的选中状态? 2. `data()` 方法与 `attr("data-*")` 有什么区别? 3. 为什么修改 `disabled` 属性时推荐用 `prop()`? 4. 在动态生成的元素上,`attr()` `prop()` 哪个更可靠? 5. 如何用原生 JavaScript 实现类似 `prop()` 的功能?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值