Javascript函数切换不同按钮的文本

时间:2017-09-20 05:46:50

标签: javascript html

我对javascript和网络开发非常陌生。我正在构建一个页面,其中有多个区域供用户添加和保存文本。每个文本区域都有一个具有不同ID的按钮,用于在只读和可编辑之间切换文本区域以及按钮的文本&# 34;保存"当文本区域可编辑时,"编辑"当文本是只读的时候。

以下功能适用于1个按钮(editNameBtn)。我的问题是有没有办法写一个函数,我可以传递每个按钮的ID来切换文本?而不是为每个按钮设置不同的功能w'不同的身份。

function toggleText(editNameBtn) {

 var el = document.getElementById("editNameBtn").textContent;

  if (el == "Edit"){
    el = "Save";
  } else {
    el = "Edit";
  }
  document.getElementById("editNameBtn").textContent = el;
}

5 个答案:

答案 0 :(得分:4)

关闭。您需要按原样传递函数的参数,而不是用双引号将其包装。

更改

document.getElementById('name').textContent = (displayName.split(' '))[0];

var el = document.getElementById("editNameBtn").textContent;

答案 1 :(得分:1)

只需将按钮的ID传递给您的函数,就像字符串一样。

function toggleText(buttonID) {
    var el = document.getElementById(buttonID).textContent;

    if (el == "Edit") {
        el = "Save";
    } else {
        el = "Edit";
    }

    document.getElementById(buttonID).textContent = el;
}

答案 2 :(得分:1)

 function toggleText(editNameBtn) {
 var el = document.getElementById("editNameBtn").textContent;
  if (el == "Edit"){
    el = "Save";
  } else {
    el = "Edit";
  }
  document.getElementById("editNameBtn").textContent = el;
}

在getElementById的上述函数中,您将editNameBtn作为字符串传递,但它是一个argumrnt。请删除引号。下面的snipet解决了isuee



 function toggleText(editNameBtn) {
 var el = document.getElementById(editNameBtn).textContent;
  if (el == "Edit"){
    el = "Save";
  } else {
    el = "Edit";
  }
  document.getElementById(editNameBtn).textContent = el;
  
}

<button id="PASSIDHERE" onclick="toggleText('PASSIDHERE')">Edit</button>
<!-- single qutoes in toggleText('PASSIDHERE') and the argument should be same as id -->
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您的代码应该像这样更新。

function toggleText(btnId) {

 var el = document.getElementById(btnId).innerHTML;


  if (el == "Edit"){
    el = "Save";
  } else {
    el = "Edit";
  }
  document.getElementById(btnId).innerHTML= el;
}

你的Html应该是这样的

<button id='editNameBtn' onclick='toggleText("editNameBtn")'>Edit</button>

答案 4 :(得分:0)

 function toggleText(btn_id) {
 var el = document.getElementById(""+btn_id).textContent;
  if (el == "Edit"){
    el = "Save";
  } else {
    el = "Edit";
  }
  document.getElementById(""+btn_id).textContent = el;
}

function toggleText(btn_id) {
 var el = document.getElementById(""+btn_id).textContent;
  if (el == "Edit"){
    el = "Save";
  } else {
    el = "Edit";
  }
  document.getElementById(""+btn_id).textContent = el;
}
<button id="id1" onclick="toggleText('id1')">Edit</button>