我对JavaScript相对陌生,我不确定如何将您在文本框中键入的内容保存在变量中,然后在末尾添加@(例如,您在mooflemoos247中输入,然后单击按钮,它会运行一个在末尾添加随机@的函数,如@gmail.com(。
我也是堆栈溢出的新手,所以如果我问对了问题,请告诉我。
我目前有:
document.getElementById("textBox").value = document.getElementById("textBox").value + email[Math.floor(Math.random() * email.length)]
我知道当我添加@,然后将@作为变量的一部分时,但我不知道该怎么做。感谢您的帮助:(
首先,您需要检查是否已经有任何email provider
附加到字符串中。如果是,则在@
之前获得address
,并将其附加随机email service provider
。
const input = document.querySelector("#textBox");
const button = document.querySelector("button");
const emailProviders = [
"gmail.com",
"yahoo.com",
"hotmail.com",
"aol.com",
"msn.com",
"outlook.com",
"live.com"
]
button.addEventListener("click", () => {
let inputValue = input.value;
if (inputValue.match(/@/)) inputValue = inputValue.split("@")[0];
input.value = `${inputValue}@${emailProviders[Math.floor(Math.random() * emailProviders.length)]}`;
})
<input type="text" id="textBox" />
<button> Append text </button>
尝试这个
let array = ["@gmail.com","@yahoo.com","@example.com"];
function add(){
let input_field = document.getElementById("email");
let input_value = input_field.value.split("@")[0];
input_field.value = input_value + array[Math.floor(Math.random() * array.length)]
}
<input type="text" id="email" />
<button onclick="add()">Add @</button>