多个函数onclick addeventlistener

时间:2013-09-20 01:03:36

标签: javascript

我有以下代码,当由onclick 触发时有效: onClick =“change('imgA');”

function change(v) {
    var target = document.getElementById("target");
    if (v == "imgA") {
        target.className = "cast1";
    } else if (v == "imgB") {
        target.className = "cast2";
    } else if (v == "imgC") {
        target.className = "cast3";
    } else if (v == "imgD") {
        target.className = "cast4";
    } else {
        target.className = "chart";
    }
}

只要将此结果存储到id'target',我如何再次执行相同的功能,但使用不同的classNames('bio1'而不是'cast1'等)。然后将结果保存到不同的ID?

每次我尝试过都没有达到这一点。

1 个答案:

答案 0 :(得分:1)

你可以尝试:

function change(v, id) {
  var areas;
  if( id == 'target' ) {
    areas = 'cast';
  } else {
    areas = 'bio';
  }
  var target = document.getElementById(id);
  if (v == "imgA") {target.className = areas+"1";}
  else if (v == "imgB") {target.className = areas+"2";}
  else if (v == "imgC") {target.className = areas+"3";}
  else if (v == "imgD") {target.className = areas+"4";}
  else {target.className = "chart";}
}