Jquery为input赋值时的disabled与readonly

        最近遇到一个问题:使用JQuery为input标签赋值,使用$("#XX表单").serialize()将数据提交到后台,发现后台有一项数据接收不到,跟踪发现该标签使用了JQuery为其动态赋值,且:使用了$("#该项数据ID").attr("disabled","disabled");

        一番查询,发现上面两种方式存在冲突:使用$("#该项数据ID").attr("disabled","disabled")后$("#XX表单").serialize()将失效,然后将$("#该项数据ID").attr("disabled","disabled")改为了$("#该项数据ID").attr("readonly","readonly");

        在排查期间发现一个有趣的现象:使用$("#数据ID").val(data);进行赋值时在前端页面的F12找不到该项input标签的value属性及其对应的值,使用$("#数据ID").attr("value", data); 则可以找到,查了一下API:

.attr( attributeName, value )方法的说明为:

.attr( attributeName, value )

Description: Set one or more attributes for the set of matched elements.

attributeName
Type: String
The name of the attribute to set.

value
Type: String or Number or Null
A value to set for the attribute. If null, the specified attribute will be removed (as in .removeAttr()).

.val( value )方法的说明:

.val( value )

Description: Set the value of each element in the set of matched elements.

.val( value )
value
Type: String or Number or Array
A string of text, a number, or an array of strings corresponding to the value of each matched element to set as selected/checked.

Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.

搞定,Mark一下备查。最后,献上JQuery的API:https://api.jquery.com/

你可能感兴趣的:(前端)