简体   繁体   English

JavaScript:检查html p标签是否为空

[英]JavaScript: check if html p tag is empty

I have the following in my project: 我的项目中有以下内容:

 function check() { var empt = document.getElementById('xyz1').value; if (empt == "") { alert("Please input a Value"); return false; } else { return true; } } 
 <a href="test.html" role="button" name="weiter" id="weiter" onclick="check();">Go</a> <p id="xyz1"></p> 

Something I am doing wrong. 我做错了。 I always get to the page test.html. 我总是进入test.html页面。 The check is not working. 支票无效。 Is it even possible, to check if ap tag is empty? 甚至有可能检查ap标签是否为空?
Goal is, if there is nothing in the p tag to get an alert and if there is a string or number getting to the linked page test.html I would like to work in pure JavaScript (no jQuery). 目标是,如果p标记中没有任何东西可以得到警报,并且链接页面的字符串或数字是否为test.html,我想使用纯JavaScript(无jQuery)。

It's innerHTML instead of value. 它是innerHTML而不是价值。 Also, check for null. 另外,请检查是否为空。

 function check() { var empt = document.getElementById('xyz1').innerHTML; if (empt == null || empt == "") { alert("Please input a Value"); return false; } else { return true; } } 
 <a href="test.html" role="button" name="weiter" id="weiter" onclick="check();">Go</a> <p id="xyz1"></p> 

  function check() { event.preventDefault(); var empt = document.getElementById('xyz1').innerHTML; if (empt == null || empt == "") { alert("Please input a Value"); return false; } else { return true; } } 
 <a href="test.html" role="button" name="weiter" id="weiter" onclick="check();">Go</a> <p id="xyz1"></p> 

Function must be event prevent default otherwise run href after on click event. 函数必须是事件阻止默认值,否则在单击事件后运行href。

Another Method 另一种方法

onclick="return check()"

  function check() { var empt = document.getElementById('xyz1').innerHTML; if (empt == null || empt == "") { alert("Please input a Value"); return false; } else { return true; } } 
 <a href="test.html" role="button" name="weiter" id="weiter" onclick="return check();">Go</a> <p id="xyz1"></p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM