jQuery入门(3) 设置DOM属性与获取DOM属性
扫描二维码
随时随地手机看文章
//设置input的value
$("#edittext").val("99");
//获取input的value
var ret = $("#edittext").val();
console.log(ret);
hello
hello
//设置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());
}
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;
}
} );
}