将值重新分配给变量

Reassigning a value to a variable

本文关键字:分配 变量 新分配      更新时间:2023-09-26

我觉得我一定在这里错过了一些非常明显的东西。我从div 中获取文本并使用 if 语句将变量的值重新分配给"javascript"(如果它是"HTML"),但这似乎根本不起作用。

有人可以帮助我吗?

var currentChoice = $('#contentSelector').text();      
var newChoice = currentChoice;
if (currentChoice == 'HTML') {
  currentChoice = 'Javascript';
};
alert(currentChoice);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="contentSelector"> HTML </div>

谢谢

"HTML"周围有空格,因此可能不匹配。"HTML"不同于"HTML"。

这样做,它$.trim($('#contentSelector').text());

元素

HTML文本值的两侧都有空格。在测试 if 语句中的值之前,可以使用 trim() 删除这些内容:

var currentChoice = $('#contentSelector').text().trim();  

如果你已经在使用 jquery,为什么不呢:

var $currentChoice = $('#contentSelector')      
if ($currentChoice.text().toString() == "HTML"){
    $currentChoice.text('Javascript');
};