js怎么做到字符串和星号隐藏来回切换显示?

比如要在页面显示一个字符串
abcdskldf-sdfljkjsjdfl-sdfdsfs
隐藏显示后是:abcdskldf* <显示>(这是个按钮点击后变为隐藏)
需求:点击显示按钮隐藏后的字符串展示回完整的状态,
有大佬提供一下方便切换隐藏显示的思路吗

阅读 2.8k
3 个回答
原生js写法
<html lang="en">
<body>
    <div id="cont">abcdskldf*</div>
    <button id="btn">显示</button>
    <script>
        let cont = document.getElementById('cont')
        let btn = document.getElementById('btn')
        btn.onclick = function () {
          cont.innerHTML = cont.innerHTML === 'abcdskldf*' ? 'abcdskldf-sdfljkjsjdfl-sdfdsfs' : 'abcdskldf*'
          btn.innerHTML = cont.innerHTML === 'abcdskldf*' ? '显示' : '隐藏'
        }
    </script>
</body>
</html>
vue写法
<template>
<div>
<div>{{cont}}</div>
<button @click="changeCont">{{statusTxt}}</button>
</div>
</template>

<script>
export default{
  data () {
    return {
      cont: 'abcdskldf*',
      statusTxt: '显示'
    }
  },
  methods: {
    changeCont () {
      this.cont = this.cont === 'abcdskldf*' ? 'abcdskldf-sdfljkjsjdfl-sdfdsfs' : 'abcdskldf*'
      this.statusTxt = this.cont === 'abcdskldf*' ? '显示' : '隐藏'
    }
  }
}
</script>
let isShow = true;
let str = 'abcdskldf-sdfljkjsjdfl-sdfdsfs';
const strSplitArray = str.split('-');
const onClick = ()=>{
    isShow = !isShow;
    str = isShow ? strSplitArray.join('-'):`${strSplitArray[0]}*`;
}

点击时,触发onClick函数,str值即为abcdskldf-sdfljkjsjdfl-sdfdsfs或为abcdskldf*,按钮文案以isShow进行判断是展示显示还是隐藏

让你看不懂(≧▽≦)

<!DOCTYPE html>
<html lang="en">

<body>
  <h2 id="e4e"></h2>
  <button id="btn"></button>
</body>
<script>
  const ele = document.querySelector('#e4e')
  const btn = document.querySelector('#btn')

  btn.addEventListener('click', (() => {
    const sourceStr = 'abcdskldf-sdfljkjsjdfl-sdfdsfs'
    const handledStr = `${sourceStr.slice(0, 9)}*`
    const btnBranch = ['隐藏', '显示']

    /** @params 判断是否显示 */
    let isShowFull = false

    // # 初始化数据
    ele.innerHTML = isShowFull ? handledStr : sourceStr
    btn.innerHTML = isShowFull ? btnBranch[1] : btnBranch[0]

    return function l({ target }) {
      isShowFull = !isShowFull
      ele.innerHTML = isShowFull ? handledStr : sourceStr
      btn.innerHTML = isShowFull ? btnBranch[1] : btnBranch[0]
    }
  })())

</script>

</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏