通过jQuery获取input数据及html中name的使用

猿友 2021-01-25 15:01:00 浏览数 (2000)
反馈

在前端开发中,使用表单会进行跳转,有时候并不需要这个的。这里通过 jQuery,使用 AJAX 直接发送 Json 数据。

运行截图如下:

微信截图_20210125113716

界面如下:

微信截图_20210125113805

这里可以看到

微信截图_20210125113821

div 里面是 group1,然后后面都是 input1,input2 等等。

并且有一个 group2

微信截图_20210125113839

name 和上面 group1一样。
微信截图_20210125113855

通过这种方式,获取,如下,group1下的input[name=input1]的值,等等。

在 index.html 下面

img

可以知道先加载 jquery.min.js,再加载 test.js

而加载到 test.js

微信截图_20210125113907

但界面加载完成。就运行 init(),这个 init 中调用了绑定函数,绑定了2个按钮。

程序源码如下:

index.html

<html>
<head>
<title>Test</title>
</head>
<body>
<div class="group1">
<label >名称1_1</label>
<input type="text" name="input1"></input>
<br/>
<label>名称1_2</label>
<input type="text" name="input2"></input>
<br/>
<label>名称1_3</label>
<input type="text" name="input3"></input>
<br/>
<label>名称1_4</label>
<input type="text" name="input4"></input>
<br/>
<button class="do-btn1">点击</button>
</div>
<br/>
<br/>
<div class="group2">
<label>名称2_1</label>
<input type="text" name="input1"></input>
<br/>
<label>名称2_2</label>
<input type="text" name="input2"></input>
<br/>
<label>名称2_3</label>
<input type="text" name="input3"></input>
<br/>
<label>名称2_4</label>
<input type="text" name="input4"></input>
<br/>
<button class="do-btn2">点击</button>
</div>
</body>
<script src="jquery.min.js"></script>
<script src= "test.js"></script>
</html>

test.js

;
var member_do1 = {
init: function(){
this.eventBind();
},
eventBind:function(){
$(".group1 .do-btn1").click(function(){
$.ajax({
url: "https://www.baidu.com",
type: "POST",
data:{
value1:$(".group1 input[name=input1]").val(),
value2:$(".group1 input[name=input2]").val(),
value3:$(".group1 input[name=input3]").val(),
value4:$(".group1 input[name=input4]").val()
},
dataType:'json',
success:function(res){
console.log(res);
}
});
})
}
};
$(document).ready(function(){
member_do1.init();
member_do2.init();
});
var member_do2 = {
init: function(){
this.eventBind();
},
eventBind:function(){
$(".group2 .do-btn2").click(function(){
$.ajax({
url: "https://www.baidu.com",
type: "POST",
data:{
value1:$(".group2 input[name=input1]").val(),
value2:$(".group2 input[name=input2]").val(),
value3:$(".group2 input[name=input3]").val(),
value4:$(".group2 input[name=input4]").val()
},
dataType:'json',
success:function(res){
console.log(res);
}
});
});
}
};


0 人点赞