gpt4 book ai didi

javascript - 如何模拟带参数的点击按钮

转载 作者:行者123 更新时间:2023-11-30 11:08:45 31 4
gpt4 key购买 nike

我正在使用引导下拉菜单,我需要在用户重新加载页面时设置默认选项(Highest positive votes)。

我试过了$('#dropdownMenuButton span.option').text("Highest positive votes");,但它并没有解决我的问题,因为我无法保留文本在 js 文件上,由于 django 框架的翻译,我需要将文本保留在 html 文件上 {% trans 'Highest positive votes' %}

HTML 代码

<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown">        
<span>{% trans 'Sorted by' %}: </span><span class="option">{% trans 'Highest positive votes' %}</span>
</button>

<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item itemSort" href="#" name='thumbsUp'>{% trans 'Highest positive votes' %}</a>
<a class="dropdown-item itemSort" href="#" name='thumbsDown'>{% trans 'Highest negative votes' %}</a>
<a class="dropdown-item itemSort" href="#" name='creationOrder'>{% trans 'Latest' %}</a>
</div>

Jquery

$('a.itemSort').click(function() {
if (this.name == 'thumbsUp') {
...
} else if (this.name == 'thumbsDown') {
...
} else if (this.name == 'creationOrder') {
...
}
$('#dropdownMenuButton span.option').text($(this).text());
});

我希望当我重新加载页面时,下拉菜单会显示文本 Highest positive votes

我正在尝试模拟点击 dropdownMenuButton 上的 thumbsUp 选项。

我该怎么做?有更好的办法解决吗?

ps.: 我尝试实现我在另一个类似问题中读到的解决方案。但这不是同一个问题。

最佳答案

您可以在按钮内创建几个 span,然后隐藏/显示所需的一个。只需要一点 CSS 和 JS

function show (classname) {
// targeting your button
const button = document.getElementById('button')
// find all possible texts inside of it
const spans = button.getElementsByTagName('span')
// hide all of them
Array.prototype.slice.call(spans).forEach(span => span.classList.remove("visible"))
// select one to be shown
const next = button.getElementsByClassName(classname)[0]
// show it
next.classList.add('visible')
}
.thumbsUp,
.thumbsDown {
display: none;
}

.visible {
display: block;
}
<button id="button">
<span class="thumbsUp visible">Thumbs UP</span>
<span class="thumbsDown">Thumbs Down</span>
</button>
<div>
<button onclick="show('thumbsUp')">Show thumbs up</button>
<button onclick="show('thumbsDown')">Show thumbs down</button>
</div>

关于javascript - 如何模拟带参数的点击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54629972/

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