我可以在onclick中使用if else语句吗?

时间:2017-10-19 06:04:33

标签: javascript

我想按字符串属性值对对象数组进行排序。 因此,如果单击按钮,则将对值进行排序。 但只有第一个if语句有效。如果我将else if语句更改为第一个if语句,它可以工作,但无论我做什么,只有第一个if语句有效。 我应该改变什么来使所有三个按钮工作?

var members = [{
  name: "jar",
  join: "2017-2",
  sex: "f",
  age: "29"
}, {
  name: "hrk",
  join: "2017-8",
  sex: "f",
  age: "21"
}, {
  name: "jjk",
  join: "2014-6",
  sex: "m",
  age: "27"
}, {
  name: "jsh",
  join: "2016-5",
  sex: "m",
  age: "37"
}, {
  name: "kks",
  join: "2014-4",
  sex: "f",
  age: "42"
}];
var list = "";


function func() {
  for (var i = 0; i < members.length; i++) {
    var val = document.getElementById('form').ans.value;

    if (members[i].join >= val || members[i].name == val || members[i].sex == val || members[i].age == val) {

      for (var key in members[i]) {
        if (key === "name" || key === "join" || key === "sex") {

          if (document.getElementById("namebtn").onclick) {
            var namesort = function(a, b) {
              if (a.name > b.name) {
                return 1;
              } else if (a.name < b.name) {
                return -1;
              }
              return 0;
            }
            members.sort(namesort);
          } else if (document.getElementById("joinbtn").onclick) {
            var joinsort = function(a, b) {
              if (a.join > b.join) {
                return 1;
              } else if (a.join < b.join) {
                return -1;
              }
              return 0;
            }
            members.sort(joinsort);
          } else if (document.getElementById("joinbtn").onclick) {
            var agesort = function(a, b) {
              if (a.age > b.age) {
                return 1;
              } else if (a.age < b.age) {
                return -1;
              }
              return 0;
            }
            members.sort(agesort);
          }
          br = " ";
        } else {
          br = "<br>";
        }
        list += members[i][key] + br;

      }
    }
  }
  document.getElementById("title").innerHTML = title;
  document.getElementById("who").innerHTML = list;
  return false;
}
<p id="title"></p>
<p id="who"></p>
<form action="#" id="form">
  <input type="text" name="ans" placeholder="year">
  <input type="submit" value="search" id="sub">
</form>
<br>
<input type="submit" onclick="func()" id="namebtn">
<input type="submit" onclick="func()" id="joinbtn">
<input type="submit" onclick="func()" id="agebtn">

5 个答案:

答案 0 :(得分:1)

if (document.getElementById('namebtn').onclick)将永远为真,因为该属性是真实的。

您是否正在尝试检查点击了哪个按钮?如果是这种情况,您的func可能应该有idevent参数(function func(btnId or e) { ... }),然后将this.id传递给func

<input type="submit" onclick="func(this.id or event)" id="namebtn">

答案 1 :(得分:0)

您可以找到当前点击事件的目标,而不是检查document.getElementById("elementid").onclick。看看这个例子。

var members = [{name: "jar",join: "2017-2",sex: "f",age: "29"}, 
               {name: "hrk",join: "2017-8",sex: "f",age: "21"},
               {name: "jjk",join: "2014-6",sex: "m",age: "27"},
               {name: "jsh",join: "2016-5",sex: "m",age: "37"},
               {name: "kks",join: "2014-4",sex: "f",age: "42"}];
var list = "";


function func(e) {
    for (var i = 0; i < members.length; i++) {
        var val = document.getElementById('form').ans.value;
        if (members[i].join >= val || members[i].name == val || members[i].sex == val || members[i].age == val) {

            for (var key in members[i]) {
                if (key === "name" || key === "join" || key === "sex") {

                    if (e.currentTarget.id == "namebtn") {
                        var namesort = function (a, b) {
                            if (a.name > b.name) {
                                return 1;
                            } else if (a.name < b.name) {
                                return -1;
                            }
                            return 0;
                        }
                        members.sort(namesort);
                    } else if (e.currentTarget.id == "joinbtn") {
                        var joinsort = function (a, b) {
                            if ((new Date(a.join)).getTime() > (new Date(b.join)).getTime()) {
                                return 1;
                            } else if ((new Date(a.join)).getTime() < (new Date(b.join)).getTime()) {
                                return -1;
                            }
                            return 0;
                        }
                        members.sort(joinsort);
                    } else if (e.currentTarget.id == "agebtn") {
                        var agesort = function (a, b) {
                            if (parseInt(a.age) > parseInt(b.age)) {
                                return 1;
                            } else if (parseInt(a.age) < parseInt(b.age)) {
                                return -1;
                            }
                            return 0;
                        }
                        members.sort(agesort);
                    }
                    br = " ";
                } else {
                    br = "<br>";
                }
                list += members[i][key] + br;

            }
        }
    }
    document.getElementById("title").innerHTML = title;
    document.getElementById("who").innerHTML = list;
    return false;
}
<p id="title"></p>
<p id="who"></p>
<form action="#" id="form">
    <input type="text" name="ans" placeholder="year">
    <input type="submit" value="search" id="sub">
</form>
<br>
<input type="submit" onclick="func(event)" value="name" id="namebtn">
<input type="submit" onclick="func(event)" value="join" id="joinbtn">
<input type="submit" onclick="func(event)" value="age" id="agebtn">

您还可以使用一些更好的日期和年龄比较方法。我在我的代码中更新了它。

答案 2 :(得分:0)

  

但只有第一个if语句有效。如果我改变其他如果   声明到第一个if语句

因为onclick值不是 falsey 而且else不太可能被执行。

  

我应该更改以使所有三个按钮都有效?

您可以通过传递排序应该发生的属性进行简化,这是演示的相同

&#13;
&#13;
var members = [
    { name: "jar", join: "2017-2", sex: "f", age: "29" },
    { name: "hrk", join: "2017-8", sex: "f", age: "21" },
    { name: "jjk", join: "2014-6", sex: "m", age: "27" },
    { name: "jsh", join: "2016-5", sex: "m", age: "37" },
    { name: "kks", join: "2014-4", sex: "f", age: "42" }
];

var list = "";

function func( prop ) 
{
  sortObjByProp(members, prop);
  list = members.map( function( memberObj ){  
     return Object.keys( memberObj ).map( function( key ){
        return "<span class='cell'>" + memberObj[ key ] + "</span>";
     }).join( "  " );
  }).join( "<br>" );
  
  document.getElementById("who").innerHTML = list;
  return false;
}

function sortObjByProp(obj, prop) 
{
  obj.sort(function(a, b) {
     return a[prop].localeCompare(b[prop]); //will work for numerics like age if the number of digits are same for all ages.
  });
}
&#13;
.cell
{
   display :inline-block;
   width: 80px;
}
&#13;
<p id="who"></p>
<form action="#" id="form">
  <input type="text" name="ans" placeholder="year">
  <input type="submit" value="search" id="sub">
</form>
<br>
<input type="submit" onclick="func('name')" id="namebtn" value="sort by name">
<input type="submit" onclick="func('join')" id="joinbtn" value="sort by join">
<input type="submit" onclick="func('age')" id="agebtn" value="sort by age">
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以通过在func函数之外定义排序函数来分离逻辑,使用.addEventListener().onclick将事件处理程序附加到每个元素。在附加到元素的事件处理程序中调用func()。使用var定义变量,特别是brlist

&#13;
&#13;
var members = [{
  name: "jar",
  join: "2017-2",
  sex: "f",
  age: "29"
}, {
  name: "hrk",
  join: "2017-8",
  sex: "f",
  age: "21"
}, {
  name: "jjk",
  join: "2014-6",
  sex: "m",
  age: "27"
}, {
  name: "jsh",
  join: "2016-5",
  sex: "m",
  age: "37"
}, {
  name: "kks",
  join: "2014-4",
  sex: "f",
  age: "42"
}];

var namesort = function(a, b) {
  if (a.name > b.name) {
    return 1;
  } else if (a.name < b.name) {
    return -1;
  }
  return 0;
}

var joinsort = function(a, b) {
  if (a.join > b.join) {
    return 1;
  } else if (a.join < b.join) {
    return -1;
  }
  return 0;
}

var agesort = function(a, b) {
  if (a.age > b.age) {
    return 1;
  } else if (a.age < b.age) {
    return -1;
  }
  return 0;
}

document.getElementById("joinbtn").onclick = function() {
  members.sort(joinsort);
  func();
};

document.getElementById("agebtn").onclick = function() {
  members.sort(agesort);
  func();
}

document.getElementById("namebtn").onclick = function() {
  members.sort(namesort);
  func();
};

function func() {
  var br = "";
  var list = "";
  for (var i = 0; i < members.length; i++) {
    var val = document.getElementById('form').ans.value;

    if (members[i].join >= val || members[i].name == val || members[i].sex == val || members[i].age == val) {

      for (var key in members[i]) {
        if (key === "name" || key === "join" || key === "sex") {
          br = " ";
        } else {
          br = "<br>";
        }
        list += members[i][key] + br;

      }
    }
  }
  // document.getElementById("title").innerHTML = title;
  document.getElementById("who").innerHTML = list;
  return false;
}
&#13;
<p id="title"></p>
<p id="who"></p>
<form id="form">
  <input type="text" name="ans" placeholder="year">
  <input type="button" value="search" id="sub">
</form>
<br>
<input type="button" id="namebtn" value="name">
<input type="button" id="joinbtn" value="join">
<input type="button" id="agebtn" value="age">
&#13;
&#13;
&#13;

答案 4 :(得分:0)

正如@ nitheesh正确建议的那样,您应该使用event.currentTarget.id代替onClick

指点很少,

注意:这些指针仅仅是建议,并且高度依赖于个人的观点。如果您认为他们无论如何都会帮助您,请使用它们。如果没有,请忽略它们。

  • 如果您定义document.getElementById(...).onClick = function(){...},则会替换原始处理程序。它甚至可能打破逻辑
  • 在标记上设置处理程序会使代码与HTML一起呈现时更加脆弱,因此任何查看页面源代码的人都可以看到名称。您应该使用addEventListener
  • 您应该尝试更多地重用您的代码。而不是具有多个排序函数,具有返回排序函数的通用函数。这样,您可以用更少的代码处理更多案例。
  • 尝试使用更好的命名约定。 func是一个糟糕的函数名称。函数名称应表示其用途。

&#13;
&#13;
var members = [{ name: "jar", join: "2017-2", sex: "f", age: "29" }, { name: "hrk", join: "2017-8", sex: "f", age: "21" }, { name: "jjk", join: "2014-6", sex: "m", age: "27" }, { name: "jsh", join: "2016-5", sex: "m", age: "37" }, { name: "kks", join: "2014-4", sex: "f", age: "42" }];

function getMySortFn(key) {
  return function(a, b) {
    return a[key].localeCompare(b[key]);
  }
}

function func(e) {
  var list = "";
  for (var i = 0; i < members.length; i++) {
    var val = document.getElementById('form').ans.value;

    if (members[i].join >= val || members[i].name == val || members[i].sex == val || members[i].age == val) {
    var shouldSort = ['namebtn', 'joinbtn', 'agebtn'].indexOf(e.currentTarget.id) > -1;
      for (var key in members[i]) {
        if (key === "name" || key === "join" || key === "sex") {
          if(shouldSort) {
            members.sort(getMySortFn(e.currentTarget.id.replace('btn', '')));
          }
          br = " ";
        } else {
          br = "<br>";
        }
        list += members[i][key] + br;
      }
    }
  }
  document.getElementById("title").innerHTML = title.innerHTML;
  document.getElementById("who").innerHTML = list;
  return false;
}

var btns = document.querySelectorAll('input[type="submit"]');
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener('click', func);
}
&#13;
<p id="title"></p>
<p id="who"></p>
<form action="#" id="form">
  <input type="text" name="ans" placeholder="year">
  <input type="submit" value="search" id="sub">
</form>
<br>
<input type="submit" id="namebtn" value='name'>
<input type="submit" id="joinbtn" value='join'>
<input type="submit" id="agebtn" value='age'>
&#13;
&#13;
&#13;