用链接

时间:2016-07-04 09:37:57

标签: javascript knockout.js hyperlink

我需要遍历一个数组并将项目与字符串进行比较,如果它包含数组中的项目,则将字符串中的文本更新为链接

有没有办法在viewModel中构建DOM标记字符串?

到目前为止,基于Jeroen的答案,我能够做到这一点。如果您点击运行代码段,您可以看到它正在做什么而不是我需要它做什么



$(function() {
  var tvm = new testViewModel();
  tvm.addLink();
  ko.applyBindings(tvm);
})
var Link = function(txt, hrf) {
  this.txt = ko.observable(txt);
  this.hrf = ko.observable(hrf);
}
var testViewModel = function() {
  var self = this;
  self.links = ko.observableArray([]);
  self.addLink = function() {
    console.log('here');
    self.links.push(new Link('Sam', 'Open?name=Sam'));
    self.links.push(new Link('Test', 'Open?name=Test'));
    self.links.push(new Link('Maria', 'Open?name=Maria'));
    var wholeStr = 'Maria is testing the new system';
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is what it's doing: <div data-bind="foreach: links">
  <a data-bind="attr: { href: hrf }, text: txt"></a>
</div>
This is what I want:
<a href="Open?name=Maria">Maria</a> is <a href="Open?name=Test">test</a>ing the new system. 
&#13;
&#13;
&#13;

现在,它只是从数组中写出链接而不是整个字符串,其中部分链接是链接。我在哪里可以指定匹配数组中文本的文本应该用链接替换?

谢谢

0 个答案:

没有答案