使用HTML的href传递参数:如何自动传递元素class值?
如何自动传递按钮自身的class作为URL参数?
当然可以实现!你现在手动写死参数的方式确实不够灵活,其实只需要在点击事件里利用this关键字获取当前按钮的class属性,就能自动拼接对应的参数了。
最简单的实现(按钮只有单个主题class)
如果你的按钮只带有light或dark这类单一主题class,直接用this.className就能拿到当前的class值,拼接到URL里就行:
<button class="light" id="pg1" onclick="window.location.href = '1.html?theme=' + this.className;">page 1</button>
把按钮的class改成dark后,点击时会自动跳转到1.html?theme=dark,完全不用手动修改onclick里的代码。
处理多个class的情况
如果按钮同时有多个class(比如class="btn dark"),可以用classList来判断当前按钮包含哪个主题class:
<button class="btn dark" id="pg1" onclick=" // 判断当前按钮的class里包含dark还是light const activeTheme = this.classList.contains('dark') ? 'dark' : 'light'; window.location.href = '1.html?theme=' + activeTheme; ">page 1</button>
进阶:提取特定格式的class
如果你的主题class是带前缀的(比如theme-light、theme-dark),还可以用正则来精准提取主题值:
<button class="theme-light btn" id="pg1" onclick=" // 匹配theme-开头的class,提取后面的主题名 const themeMatch = this.className.match(/theme-(\w+)/); const activeTheme = themeMatch ? themeMatch[1] : 'light'; // 默认值设为light window.location.href = '1.html?theme=' + activeTheme; ">page 1</button>
这样不管按钮的class怎么组合,只要包含theme-xxx格式的class,就能自动提取对应的主题参数传递过去。
内容的提问来源于stack exchange,提问作者akash
相关产品推荐
相关产品推荐

