设置与获取为同一个方法,不传入参数为获取,传入参数为设置
input元素value:val方法
<body>
<input id="edittext" type="text">
<button id="button_test">button</button>
</body>
//设置input的value
$("#edittext").val("99");
//获取input的value
var ret = $("#edittext").val();
console.log(ret);
常规元素text:html方法
<body>
<a class="a">hello</a>
<p class="p">hello</p>
</body>
//设置a标签的text
$(".a").html("99");
//获取a标签的text
var ret = $(".a").html();
console.log(ret);
//设置p元素的text
$(".p").html("pppppp");
//获取a元素的text
ret = $(".p").html();
console.log(ret);
样式表:css方法 css(属性,值)
var $obj =$(".a");
//设置css的color属性
$obj.css("color","red");
//获取css的color属性 color类型返回 rgb(255,0,0) 类型string
var m_color = $obj.css("color");
console.log(m_color+"类型:"+typeof m_color);
迭代:
var $obj =$(".a");
for(var x=0;x<$obj.length;x++)
{
$obj.eq(x).html("im index:"+x);
}
$obj= $(".a");//可省略 前面已经得到
for(var x=0;x<$obj.length;x++)
{
console.log($obj.eq(x).html());
}
具体可查看jQuery var函数实现
val: function( value ) {
var hooks, ret, isFunction,
elem = this[ 0 ];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] ||
jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if (
hooks &&
"get" in hooks &&
( ret = hooks.get( elem, "value" ) ) !== undefined
) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace( rreturn, "" ) :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each( function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
} );
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
} );
}