2 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
jQuery attr()、prop() 方法都可以用于獲取或設(shè)置屬性值:
1 2 | $("input:text").attr("name"); // 獲取name屬性值 $("input:text").attr("name",str); // 設(shè)置name屬性值為str |
實(shí)例演示:先設(shè)置文本框的屬性值,然后獲取
示例代碼如下
創(chuàng)建Html元素
1 2 3 4 5 6 7 8 | <div class="box"> <span>設(shè)置和獲取name屬性值:</span> <div class="content"> <label>姓名 </label><input type="text" class="test" value=""> </div> <label>設(shè)置name屬性值</label><input type="text" name="set" value=""><input type="button" name="btn1" value="確定"> <input type="button" name="btn2" value="獲取文本框name值"> </div> |
設(shè)置css樣式
1 2 3 4 5 | div.box{width:300px;height:250px;padding:10px 20px;margin:20px;border:4px dashed #ccc;} div.box>span{color:#999;font-style:italic;} div.content{width:250px;height:50px;margin:10px 0;padding:5px 20px;border:2px solid #ff6666;} input[type='text']{width:200px;height:40px;border:1px solid #6699cc;} input[type='button']{height:30px;margin:10px;padding:5px 10px;} |
編寫jquery代碼
1 2 3 4 5 6 7 8 9 10 | $(function(){ // 設(shè)置屬性值 $("input:button[name='btn1']").click(function() { $("input.test").attr("name",$("input:text[name='set']").val()); }); // 獲取屬性值 $("input:button[name='btn2']").click(function() { alert($("input.test").attr("name")); }); }) |

TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊
jquery中attr 方法可以修改元素的任何屬性,像name,href,src都可以通過(guò)這個(gè)方法來(lái)進(jìn)行修改。
例如: $('input[name="sno"]').attr('name','account');
attr 接收兩個(gè)參數(shù) 第一為屬性名,第二為屬性值。同時(shí)attr參數(shù)還支持對(duì)象的方式,方便同時(shí)對(duì)多個(gè)屬性進(jìn)行修改。
例如: $('input[name="sno"]').attr({'name':'account','href':'test-href'});
- 2 回答
- 0 關(guān)注
- 787 瀏覽
添加回答
舉報(bào)