我試圖做到這一點,所以如果 var 文本沒有 https:// 我這樣做了,但如果它已經在它沒有添加 https:// 的文本中,我想做到這一點
document.addEventListener("keydown", function (event) {
if (event.keyCode === 13) {
var text = "https://" document.getElementById("input").value;
document.getElementById("iframe").src = text;
document.getElementById("iframe").height = "100%";
document.getElementById("iframe").width = "100%";
document.getElementById("content").innerHTML = '';
}
});
uj5u.com熱心網友回復:
只需檢查輸入startsWith是否是您要查找的內容..
let input = document.getElementById("input").value;
let text = input.startsWith("https://") ? input : "https://" input;
如評論中所述,此處使用了條件三元運算子,您可以在此處找到更多資訊:條件(三元)運算子
uj5u.com熱心網友回復:
一種方法是:
// here we cache the value of the <input> element:
let value = document.getElementById("input").value,
// we define the protocol we're looking for:
protocol = 'https://',
// we then assign the text, using a template-literal string,
// first we use a conditional operator:
// which returns a Boolean (true/false), if the
// String we test starts with the supplied String
// ('protocol'); if it does we return an empty string
// and if not we return the protocol variable; and then
// that's concatenated with the existing 'value'
// variable:
text = `${value.startsWith(protocol) ? '' : protocol}${value}`;
參考:
- 條件運算子。
String.prototype.startsWith().- 模板文字。
uj5u.com熱心網友回復:
嘗試使用包含函式來檢查字串是否包含另一個字串。
document.addEventListener("keydown", function (event) {
if (event.keyCode === 13) {
let text = document.getElementById("input").value;
let src = text.includes("https://") ? text : "https://" text;
document.getElementById("iframe").src = src;
document.getElementById("iframe").height = "100%";
document.getElementById("iframe").width = "100%";
document.getElementById("content").innerHTML = '';
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459137.html
標籤:javascript 变量
