我现在有一个自定义DuckDuckGo搜索栏的代码:
<form action="https://duckduckgo.com/" method="get" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
</form>当您在框中输入文本并按enter键时,它会自动打开https://duckduckgo.com/?q={{SEARCH}}。
如果输入了一个域,如何才能使这个栏转到域呢?最优的情况是,它不会验证域,只是如果它看到模式xxxx.*中没有空格的字符串,它就会在一个新的选项卡中打开该页面。
谢谢你的帮助!
发布于 2019-04-07 19:32:59
解决这个问题的一种方法是捕获表单的submit事件,分析输入值,当输入值是域时,打开一个带有域的新窗口,然后返回false取消提交。如果不是有效域,则让表单像往常一样返回true。
您的html:
<form action="https://duckduckgo.com/" method="get" onsubmit="return decideWhatToDo()" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
<input type="submit" />
</form>您的javascript:
function decideWhatToDo() {
let inputValue = document.getElementById('field-3').value;
if (isDomain(inputValue)) {
// the form won't be sent and a new window will open requesting the domain
if (!startsWithProtocol(inputValue)) {
inputValue = 'http://' + inputValue;
}
window.open(inputValue, '_blank');
return false;
}
// Proceed to send the form as usual
return true;
}
function startsWithProtocol(value) {
return /^((https?|ftp|smtp):\/\/)/.test(value);
}
function isDomain(value) {
return /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$/.test(value);
}发布于 2019-04-07 19:28:43
因此,处理它的一种方法是使用if条件,并根据识别域名的RegExp检查字符串。
这里有一个漂亮的,你可以用:
/[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/我假设您不需要帮助从文本字段或实际重定向中获取值。不过,如果你需要更多的帮助,下面的评论,我会发布一个更完整的答案。下面的代码将帮助您到达您想要的位置:
var domainRegExp = /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
var pass = domainRegExp.test('test.com')
var fail = domainRegExp.test('test')
console.log(pass, 'pass')
console.log(fail, 'fail')
因此,正如您所看到的,'pass‘变量中的值为true,而'fail’为false。
https://stackoverflow.com/questions/55562399
复制相似问题