您好我创建了一个带有条件语句的HTML和JavaScript网站,如果您打个招呼,它会回复一些内容。
function myFunction() {
var letter = document.getElementById("myInput").value.toLowerCase(),
text;
if (letter === "hi im jack") {
text = "Spot on! Good job!";
} else if (letter === "hi" || letter === "hey" || letter === "hello" || letter === "hi there") {
text = "Hi I Am Mike";
}
document.getElementById("demo").innerHTML = text;
}
<input id="myInput" type="text" onkeyup="myFunction()" style="font-size: 30pt; height: 50px; width: 600px;">
<button onclick="myFunction()" style="font-size: 30pt; height: 50px; width: 200px;">ENTER</button>
<p id="demo">result here</p>
问题是我需要为其中一个回复添加图像而不是文本。我还需要知道如何让它自动发送到不同的网站。我正在寻找一些非常简单的东西,如果可能的话,可以取代“text ==”。
答案 0 :(得分:1)
请参阅此答案,它可能会有所帮助:How to display image with javascript?
放置以下内容而不是文本行,它应该可以工作。
text = ('< img src="+http:xxx+"/>');
答案 1 :(得分:1)
使用与您使用的代码相同的代码,并为文本变量分配新值,如下所示:
function myFunction() {
var letter = document.getElementById("myInput").value.toLowerCase(),
text;
if (letter === "hi im jack") {
text = '<img src="imageName.jpg" width="200" height="200" />'; //Show an image
} else if (letter === "hi" || letter === "hey" || letter === "hello" || letter === "hi there") {
location.href = 'http://www.websitename.com'; //Redirect automatically
}
document.getElementById("demo").innerHTML = text;
}
答案 2 :(得分:0)
你可以使用switch语句而不是if
一个switch语句有点像if else条件和一些语法糖,例如
switch( chackVariable ){
case value:
doSomeStuff()
break; // break will end the switch statement and prevent testing any other cases
}
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/switch
然后问题的另一部分与创建图像有关,我只是使用innerHTML将其创建为字符串,如前所述。
function myFunction() {
// try to save your helper variables at the top of the function
var
input = document.getElementById("myInput"),
demo = document.getElementById("demo"),
letter = input.value.toLowerCase(),
text;
switch( letter ){
case 'hi im jack':
text = 'Spot on! Good Job!';
break;
// you can do && conditions by doing multiple cases for one set of functionality
case 'hi':
case 'hello':
case 'hi there':
text = 'Hi I Am Mike';
break;
case 'image':
text = '<img src="http://lorempixel.com/100/100/" />';
break;
case 'personal space':
// you can redirect the page with js by setting the value for document.location.href
// it wont work on stack however due to the same origin policy and settings on the other web page
document.location.href = 'https://www.youtube.com/embed/2DfmDuOxcN8';
break;
// default will be run if none of the cases match or the previous cases did not have a break
default:
text = 'result here';
}
demo.innerHTML = text;
}
<input id="myInput" type="text" onkeyup="myFunction()" style="font-size:30pt;height:50px;width:600px;">
<button onclick="myFunction()" style="font-size:30pt;height:50px;width:200px;">ENTER</button>
<p id="demo">result here</p>