Discuss / JavaScript / ^_^这位兄台的最屌

^_^这位兄台的最屌

Topic source

jaychang87

#1 Created at ... [Delete] [Delete and Lock User]
json = {};
$('#test-form [type!=submit]').map(function(){
  if(this.type !== "radio" || this.checked){
     json[this.name] = this.value;
  }
});
json = JSON.stringify(json);

iridiumcao

#2 Created at ... [Delete] [Delete and Lock User]

同感。 而且这段代码很有美感

您好、我想问一下那个

json={};
var input = $('#test-form :input[type!=submit]');
input.map(function(){
if(this.type !== "radio" || this.checked){   json[this.name] = this.value; }
});

json=JSON.stringify(json);在此插入代码

if(this.type !== "radio" || this.checked) 这个判断怎么理解,其中的radio为何要单独排除呢、还有排除了gender之后为何json还能获取到gender的值呢、是怎么获取的呢?小白求解答。

旺楠楠

#5 Created at ... [Delete] [Delete and Lock User]

1.radio被排除是因为需要获取的内容不一样。对于其他input而言,我们需要获取其值,而对于radio而言,我们不是需要他的“值“,而是需要知道哪一项被选中了。 2.

if(this.type !== "radio" || this.checked)

请看判断条件,其中写明了,“如果不是单选“为true,“如果是单选,并且它被选中了“也是true。

表示一脸懵逼啊

jinglepper

#7 Created at ... [Delete] [Delete and Lock User]

上面的哥们的代码确实写得简洁,赞一个 写惯了python,觉得代码简洁就是有一种美感啊 个人觉得可以再加一个判断if(this.name),这样就不会添加undefine :undefine进去了 虽然JSON.stringify()的时候也会把它去掉,但个人感觉逻辑更清晰一些

json = {};
$('#test-form [type!=submit]').map(function(){
    if(this.name)
      if( this.type !== "radio" || this.checked){
         json[this.name] = this.value;
      }
});
json = JSON.stringify(json);

  • 1

Reply