如何使用按钮的“OnClick”功能切换名称?

摩根代码

如果“ data-count-type”值是0单击按钮时,我想将“ data-charactercount”值写入按钮。

当我再次单击按钮时,如果“ data-count-type”值为1,我想将“ data-wordcount”值写入按钮。

总之,我希望每次单击按钮时更改 2 个值之间的按钮的文本部分。(切换)

代码中有一点错误,所以它不起作用。我应该怎么安排?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button" data-count-type="0" data-wordcount="15 Words" data-charactercount="50 Character" onclick="( (this.getAttribute('data-count-type')==0) ? this.innerText = this.getAttribute('data-wordcount'), this.setAttribute('data-count-type',1)  : this.getAttribute('data-charactercount'), this.setAttribute('data-count-type',0) )">BUTTON</button>

麦克风

根据我的最佳理解,

您正在尝试创建一个按钮,您将在其中访问data-count-type的值如果data-count-type为 0,则按钮应使用data-charactercount的值更改内部文本,如果data-count-type为 1,则按钮应使用data-wordcount的值更改内部文本

这是使用内联 JS 执行上述行为的代码段。

注意:为了便于理解,我在下面有 2 个按钮的片段,1 个按钮设置为data-count-type = 0,第二个按钮设置为data-count-type = 1但是两者的内联脚本代码是相同的。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button type="button" data-count-type="1" data-wordcount="15 Words" data-charactercount="50 Character" onclick="
    if(this.getAttribute('data-count-type')==0){
        this.innerText = this.getAttribute('data-charactercount');
    } else if (this.getAttribute('data-count-type')==1){
        this.innerText = this.getAttribute('data-wordcount');
    }else{
    }
">BUTTON with data-count-type value 1</button>

<br>
<br>

<button type="button" data-count-type="0" data-wordcount="15 Words" data-charactercount="50 Character" onclick="
    if(this.getAttribute('data-count-type')==0){
        this.innerText = this.getAttribute('data-charactercount');
    } else if (this.getAttribute('data-count-type')==1){
        this.innerText = this.getAttribute('data-wordcount');
    }else{
    }
">BUTTON with data-count-type value 0</button>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章