我有一些 anchor 标记,我使用 Angular Directive(指令)来装饰(下划线)文本(以指示键盘快捷键)。到目前为止,我的代码仅在指定字符(“amt-alt-key”)位于第一个单词的开头时才有效。 我需要做的是搜索整个字符串并在第一次出现的指定字符下划线。因此,现在如果我在下面的示例中指定 amt-alt-key="A",它将按原样正常工作。然而,问题是第一次出现可能在 anchor 文本中的任何地方。任何有关编写正确 JavaScript 的帮助将不胜感激。
--杰森
In my html
<a href="#/Agent" amt-alt-key="P">Agent Data</a>
In my angular code
app.directive("amtAltKey", function () {
return {
link: function (scope, elem, attrs) {
var altKey = attrs.amtAltKey.toUpperCase();
var text = el.innerText;
var textUpper = text.toUpperCase();
var indexOfKey = textUpper.indexOf(altKey);
var newText = text.substring(0, indexOfKey);
newText += '<u>' + text.substring(indexOfKey, 1) + '</u>';
if (indexOfKey + 1 < text.length) { newText += text.substring(indexOfKey + 1); }
el.innerHTML = newText;
keyListeners[altKey] = el;
}
};
});
最佳答案
您可以使用正则表达式来检查所需的模式,并使用 replaceText
实用函数来替换匹配的模式,一旦获得文本,请替换元素的现有内容,如下所示:
.directive('amtAltKey', function () {
return {
link: function (scope, elem, attrs) {
var altKey = new RegExp(attrs.amtAltKey, 'i');
var text = elem.text();
function replaceText (txt) {
function underline(match) {
return '<u>' + match +'</u>';
}
return txt.replace(altKey, underline);
}
var newText = replaceText(text);
elem.html(newText);
}
};
});
这是一个工作示例:https://jsbin.com/zefodo/2/edit?html,js,console,output
关于javascript - 尝试使用 Javascript/Angular 在第一次出现的字符下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37049088/