我在 ko.js 中有以下 View 模型:(带有 Helplink 数组)
function initializeViewModel(vm) {
vm.helpLinks.push(new HelpLink('http://yyy.com', "Error Message/My access isn't working for..."));
vm.helpLinks.push(new HelpLink("mailto:xxx@xx.com", "Contact Research ", "ID Request/I need an ID for..."));
vm.helpLinks.push(new HelpLink("https://yyyyy.ggg.com", "Go to Assist Me form", "Assist Me Request/Please send me research on..."));
vm.helpLinks.push(new HelpLink("mailto:xxx@xx.com", "Contact Research Center", "Training request"));
}
//Html 标记
<a href="#" data-bind="visible: chosenHelpLink,
text: chosenHelpLink().linkText,
attr: { href: chosenHelpLink().url }" style="display: none;" class="primary"></a>
我想强制具有 Http/https url 的数组项在新选项卡中打开。 mailto 链接应保留原样。
我正在研究以下代码片段:
if (window.location.protocol(HelpLink) == "http:") {
window.open ...
}
不幸的是,我根本无法让该功能正常工作。 预先感谢您。
最佳答案
使用计算的和简单的独立绑定(bind)怎么样?
这是一个简短的演示,希望能对其进行解释。
function HelpLink(url, text) {
var self = this;
self.url = ko.observable(url);
self.text = ko.observable(text);
self.https = ko.computed(function(){
if(url.match(/^https/)) return true;
else return false;
})
}
function ViewModel() {
self.helpLinks = ko.observableArray();
self.helpLinks.push(new HelpLink('http://yyy.com', "Error Message/My access isn't working for..."));
self.helpLinks.push(new HelpLink("mailto:xxx@xx.com", "Contact Research ", "ID Request/I need an ID for..."));
self.helpLinks.push(new HelpLink("https://yyyyy.ggg.com", "Go to Assist Me form", "Assist Me Request/Please send me research on..."));
self.helpLinks.push(new HelpLink("mailto:xxx@xx.com", "Contact Research Center", "Training request"));
}
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="foreach: helpLinks">
<a data-bind="visible: true,
text: text,
attr: { href: url, target: https() ? '_blank' : '' }" style="display: none;" class="primary"></a><br>
</div>
编辑: 我修改了原来的答案以避免编辑 html。
对于我能想象到的每个解决方案,绑定(bind)都必须更新。 Attr 绑定(bind)允许您设置所需的任何属性。使用计算来确定是否使用 https,然后可以使用三元运算符 (?:
) 来评估是否应更改目标。
关于javascript - 检测数组项中的 Mailto 与 Http/Https 并在新选项卡中打开 Http url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45214139/