Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

c# - Toggle a button using JavaScript in an ASP.NET Core MVC app

I am trying to use JavaScript to toggle a button from the label "Connect" to the label "Forget" when clicked, and then toggle the button back to "Connect" when clicked again.

My code does not toggle the button like I expect it to. The code is in a view template (.cshtml) file in an ASP.NET Core MVC app. I am also open to answers that use JQuery to achieve my goal.

HTML:

<button type="button" class="buttonOne">Connect</button>

Code:

const $ = document.querySelector.bind(document);
$(".buttonOne").addEventListener("click", (e) => {
  let clicked = false;
  if (clicked) {
    e.target.innerText = "Forget";
  } else {
    e.target.innerText = "Connect";
  }
  clicked = !clicked;
});

$(".buttonTwo").addEventListener("click", (e) => {
  let clicked = false;
  if (clicked) {
    e.target.innerText = "Forget";
  } else {
    e.target.innerText = "Connect";
  }
  clicked = !clicked;
});

$(".buttonThree").addEventListener("click", (e) => {
  let clicked = false;
  if (clicked) {
    e.target.innerText = "Forget";
  } else {
    e.target.innerText = "Connect";
  }
  clicked = !clicked;
});
question from:https://stackoverflow.com/questions/65845056/toggle-a-button-using-javascript-in-an-asp-net-core-mvc-app

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your let clicked = false; in the beginning of the function will thwart your attempts every time.

If you set it to false at the beginning of the function it is false until you flip it to true. Next time you click, it is set to false before you test it.

I suggest you delegate. Change the class to ID and the class to button

Then delegate from a container

The test is the text on the button - no need for a clicked var now If you are going to have different languages, use a data-attribute on the button instead of some global boolean

document.getElementById("buttonContainer").addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.classList.contains("button")) {
    const text = tgt.textContent;
    console.log("Clicked",tgt.id,"to",text)
    tgt.textContent = text === "Forget" ? "Connect" : "Forget"
  }
});
<div id="buttonContainer">
  <button id="buttonOne" class="button">Connect</button>
  <button id="buttonTwo" class="button">Connect</button>
  <button id="buttonThree" class="button">Connect</button>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...