我有一个由Materialize CSS制成的下拉菜单。我正在尝试在用户单击按钮时更改“按钮”上的文本,但由于某种原因,它不会更新DOM。

var changeText;
changeText = function(){
  if(this.innerText === 'test'){
    this.innerText = 'success';
  } else {
    this.innerText = 'test';
  }

  $('.dropdown-trigger').dropdown({
    alignment: 'right',
    constrainWidth: false,
    coverTrigger: false
  });

  console.log(this.innerText);
};

$( document ).ready(function() {

  $('.dropdown-trigger').dropdown({
    alignment: 'right',
    constrainWidth: false,
    coverTrigger: false
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet"/>

<!-- Dropdown Trigger -->
<a class='dropdown-trigger btn' href='#' data-target='dropdown1'>Drop Me!</a>

<!-- Dropdown Structure -->
<ul id='dropdown1' class='dropdown-content'>
  <li><a href="#" onclick="changeText()">test</a></li>
</ul>


我尝试过重新初始化下拉触发器,希望可以更新DOM,但是它没有任何效果。尽管您可以在控制台日志中看到,但innerText已按预期进行了更改。

最佳答案

this在此引用窗口对象。所以尝试event.target

var changeText;
changeText = function(){
  if(event.target.innerText === 'test'){
    event.target.innerText = 'success';
  } else {
    event.target.innerText = 'test';
  }
  console.log(this.innerText);
};

$( document ).ready(function() {

  $('.dropdown-trigger').dropdown({
    alignment: 'right',
    constrainWidth: false,
    coverTrigger: false
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet"/>

<!-- Dropdown Trigger -->
<a class='dropdown-trigger btn' href='#' data-target='dropdown1'>Drop Me!</a>

<!-- Dropdown Structure -->
<ul id='dropdown1' class='dropdown-content'>
  <li><a href="#" onclick="changeText()">test</a></li>
</ul>

09-08 08:29