猿问

form表单提交没走onsubmit验证为什么

https://img.mukewang.com/5c48252f0001dfd604140182.jpg

https://img2.mukewang.com/5c4825320001fccd05510032.jpg

https://img3.mukewang.com/5c4825340001359208000158.jpg


加断点 点击没有进去啊

森栏
浏览 977回答 1
1回答

手掌心

提交后能够正确的走 checkTags 方法如果你是想说 ,无法验证 value的值,那么是因为你用了&nbsp;.text()&nbsp;而不是&nbsp;.val()获取值[更新]我复制的你的代码, 一模一样。表单不会被提交,因为都是返回false;如果把你的&nbsp;input[type=hidden]&nbsp;加上满足条件的value<input&nbsp;class="hiddenField"&nbsp;type="hidden"&nbsp;value="aaa,aaa,aaa">表单直接提交 说明验证成功打印出来没问题啊[更新]这是我推测的你的可能的.tags .tag使用你的代码,没有发现问题,依旧正常工作:<body>&nbsp; &nbsp; <div class="tags">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button class="tag " data-key="aaa">tag</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button class="tag " data-key="2">tag2</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button class="tag " data-key="3">tag3</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button class="tag " data-key="1">tag4</button>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; <form action="index.html" method="post" onsubmit="return checkTags();">&nbsp; &nbsp; &nbsp; &nbsp; <input class="hiddenField" type="hidden" value="">&nbsp; &nbsp; &nbsp; &nbsp; <input class="submit-tags" type="submit" value="submit">&nbsp; &nbsp; </form></body><script>&nbsp; &nbsp; var tagArr = [];&nbsp; &nbsp; $('.tags .tag').on('click', function (event) {&nbsp; &nbsp; &nbsp; &nbsp; var key = $(this).data('key');&nbsp; &nbsp; &nbsp; &nbsp; if ($(this).hasClass('active')) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(this).removeClass('active');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var flag = tagArr.indexOf(key);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tagArr.splice(flag, 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('.hiddenField').val(tagArr)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (tagArr.length >= 3) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(this).addClass('active');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tagArr.push(key);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('.hiddenField').val(tagArr)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; function checkTags() {&nbsp; &nbsp; &nbsp; &nbsp; var selectedTags = $('.hiddenField').val();&nbsp; &nbsp; &nbsp; &nbsp; console.log(selectedTags);&nbsp; &nbsp; &nbsp; &nbsp; if (selectedTags.split(',').length == 3) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('a')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }</script>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答