jq获取元素的值 、获取相同name元素的值、删除追加html内容、处理事件重复绑定问题

时间:2025-03-06 17:21:19

1jq获取元素的值

html() 
它获取的第一个匹配元素的内容,也就是所取得的标签所包含的所有东西。
text() 
它获取的是所有匹配元素的内容,而不会选取标签。 
同理,text(val)是设置所有匹配元素的文本内容
val() 
用来操作标准的表单组件对象,如button,text,hidden.
想要修改val值,一般用修改属性及值得attr()方法
        //给单选赋值
   $('.processBox').on('click','.checked',function(){
        $(this).addClass('haschecked');
        $(this).siblings().removeClass('haschecked');
        //给单选赋值
        var n = $('.choice div').index(this);
        var value = ((n+1)%2 ==0) ? 2:1;
        $(this).parent().children(' input ').val(value);
        // (n);
        // (value);

    });


它获取的第一个匹配元素的内容,也就是所取得的标签所包含的所有东西。
text() 
它获取的是所有匹配元素的内容,而不会选取标签。 
同理,text(val)是设置所有匹配元素的文本内容
val() 
用来操作标准的表单组件对象,如button,text,hidden.
想要修改val值,一般用修改属性及值得attr()方法
        //给单选赋值
   $('.processBox').on('click','.checked',function(){
        $(this).addClass('haschecked');
        $(this).siblings().removeClass('haschecked');
        //给单选赋值
        var n = $('.choice div').index(this);
        var value = ((n+1)%2 ==0) ? 2:1;
        $(this).parent().children(' input ').val(value);
        // (n);
        // (value);

    });

2.获取相同name元素的值

可以用于批量操作的情况

html 部分:

<div  class="showList"> 
     <input name="n" type= "hidden" value="1">
     <input name="n" type= "hidden" value="2"> 
     <input name="n" type= "hidden" value="3"> 
     <input name="n" type= "hidden" value="4"> 
</div>

 

jq部分:

<script>

        var numArr = []; // 定义一个空数组
        var txt = $('.showList').find(':hidden'); // 获取所有文本框
        (txt);
        for (var i = 0; i < ; i++) {
            ((i).val()); // 将文本框的值添加到数组中
        }
        var userArr = (numArr);  //将对象解析成字符串

</script>


 

3去掉追加html原始内容

 

 var name = '123';
 $('.public_tips_set:last').find('.public_tips_left p').html(name); //去掉标题
 $('.public_tips_set:last').find('.item_input input').attr('value',''); //去掉标题
 $('.public_tips_set:last').find('.tips_cancle').addClass('active_cancle'); //添加样式
$('#addPage').append(html);//追加html

 

4处理事件重复绑定问题

事件重复,一般情况 是由于用类名定义的监听事件,多个相同类名,在同一个页面时,会绑定重复。

可以在要监听事件 的元素上加一个onclick事件,再定义一个方法。

//1,获取onclick所在节点的object,需要在调用function时就把this传递过去
<button type="submit" "deletes(this)">删除</button>

//2,在function中可以用一个tmp临时存放传递过来的this
function deletes(obj){ 
	var tmp = obj;
	$(tmp).parent().remove();
}