gpt4 book ai didi

javascript - Materialise CSS Dropdown 更新 DOM insideText

转载 作者:行者123 更新时间:2023-11-30 09:11:56 24 4
gpt4 key购买 nike

我有一个用 Materialise 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>

关于javascript - Materialise CSS Dropdown 更新 DOM insideText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58011826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com