怎么用JS实现 按钮功能的循环执行?

JavaScript011

怎么用JS实现 按钮功能的循环执行?,第1张

用JS实现 点击‘提交’ 按钮变成 ‘继续添加’同时文本框变灰且只可读, 再次点击 ‘继续添加’ 文本框变回原来可写,按钮变成‘提交’。一直可以循环执行:

var bbb = document.getElementById('btn1')

bbb.onclick = function() {

var ttt = document.getElementById('btn1').value

if (ttt == '提交') {

isreadonly()

changebutton1()

} else if (ttt == '继续添加') {

readwrite()

changebutton2()

}

}

function isreadonly() {

var obj = document.getElementById("in1")

obj.setAttribute("readOnly", true)

obj.style.backgroundColor = "#d2d2d2"

var obj = document.getElementById("in2")

obj.setAttribute("readOnly", true)

obj.style.backgroundColor = "#d2d2d2"

var obj = document.getElementById("in3")

obj.setAttribute("readOnly", true)

obj.style.backgroundColor = "#d2d2d2"

}

function readwrite() {

var obj = document.getElementById("in1")

obj.setAttribute("readOnly", false)

obj.style.backgroundColor = "#ffffff"

var obj = document.getElementById("in2")

obj.setAttribute("readOnly", false)

obj.style.backgroundColor = "#ffffff"

var obj = document.getElementById("in3")

obj.setAttribute("readOnly", false)

obj.style.backgroundColor = "#ffffff"

}

function changebutton1() {

document.getElementById('btn1').value = '继续添加'

}

function changebutton2() {

document.getElementById('btn1').value = '提交'

}

应用:可将上诉代码中的文字替换,实现其它类型的循环执行。

先来看看效果图

实例代码

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> #box {margin: 100px auto width: 200px height: 150px line-height: 150px letter-spacing: 10px text-align: center font-size: 30px font-weight: bolder border: 2px solid palegreen word-wrap: break-word border-radius: 5px position: relative } #btn{position: absolute left:50% top:280px }</style> </head> <body> <div id="box"> <span>1</span> <span>2</span> <span>3</span> <span>4</span> </div> <input type="button" id="btn" value="我变了哟!"/> <script> //提取标签var box=document.getElementById("box") var span=document.getElementsByTagName("span") var btn=document.getElementById("btn") var color="" var str="0123456789abcdef" btn.onclick=function(){ for(var i=0i<span.lengthi++){//生成四位数for(var j=0j<6j++){//随机改变每个数字的颜色 color+=str.substr(parseInt(Math.random()*str.length),1)//取颜色(循环,每次提取一位,进行拼接组成6为颜色的值)}span[i].innerHTML=parseInt(Math.random()*10)//生成随机数span[i].style.color=("#"+color)//随机改变每个span的颜色color="" }} </script> </body> </html>

以上就是这篇文章的全部内容,实现代码很简单,希望对大家能有一定的帮助,如果有问题可以留言交流,小编会尽快给大家回复的。

建议使用ref,给button添加注册ref引用,然后在表单提交的时候,获取button按钮,使其disable置灰。

ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件。

<div id="app">

  <button ref="mybutton" type="primary" @click="save">保存</button>

</div> <script>

new Vue({

  el: "#app",

  data: {

  },

  methods: {

   save() {

     this.$refs.mybutton.disabled = true

    }

  }

})

</script>

<style>

:disabled{   

    border: 1px solid #DDD   

    background-color: #F5F5F5   

    color:#ACA899   

}  

</style>