问题
I'm Building a Personal Assistant with HTML5, CSS, & Javascript
This is what my current Problem is.
I Have a <div>
that contains scripts with the responses for when a Question is asked and if the question matches one it writes that response.
I Need a Script that will check if this div is empty, in Javascript, not jQuery
I need to check if the div is empty because that means there is no response.
Then for it to redirect to an the error page.
a Question & the response to it would look like this:
<script type="text/javascript">
{
var q = getValue("q");
var name = getValue("name");
}
if (q == 'Whats+up') {
document.write("Not much " + name + ".");
}
else {
}
</script>
This is the last code I tried:
<script>
var theDiv = document.getElementById("responce");
var q = getValue("q");
if(theDiv.innerHTML == ''){
window.location = 'error.html?name=Brandon&q='+q;
}
</script>
回答1:
Try this
<script type="text/javascript">
{
var q = getValue("q");
var name = getValue("name");
}
if (q == 'Whats+up') {
document.write("<div id='response_text'>"+"Not much " + name + "."+"</div>");
}
else {
}
</script>
And then:
<script>
var theDiv = document.getElementById("response_text");
var q = getValue("q");
if(theDiv==null || theDiv.innerHTML == ''){
window.location = 'error.html?name=Brandon&q='+q;
}
</script>
That being said, there are probably better/more scalable ways of doing this with ajax.
回答2:
You could check, if there are no other elements than script
s in the div
:
<script>
var theDiv = document.getElementById('responce'),
q = getValue('q'),
scripts = theDiv.getElementsByTagName('SCRIPT').length;
if (theDiv.children.length - scripts === 0) {
window.location = 'error.html?name=Brandon&q=' + q;
}
</script>
However, I'd suggested you to get rid of all inline scripts, and put them in the head
of the document or just before the closing body
tag instead.
EDIT
A quick-fix would be to move the script
below the #responce
.
来源:https://stackoverflow.com/questions/12863884/how-to-check-if-a-div-is-empty-and-then-execute-action