我目前正在开发 Angular1 应用程序。我从 API 获取数据并在 promise 解决(成功)中我首先分配不同的值(其中一些将在 View 中使用)然后,我调用一个函数来操作特定文本(添加边框和背景-颜色到句子的一方)。我使用 document.getElementById 获取标签,然后使用 label.innerHTML.replace(..)。
但是,replace 函数不执行任何操作。并且 View 不显示 {{text}} 的值。它仅在我使用 1 秒的超时时有效:替换功能有效并且 View 文本已更新(带有边框和背景颜色)。
带有 hacky setTimeout() 的 Controller 代码:
$scope.getTextAnalysis = function () {
IntentRequestService.analyzeText($scope.intentApp.id, $scope.intentvalue)
.success(function (response) {
$scope.results = response;
$scope.text = $scope.results.text;
highlightEntities($scope.results);
})
.error(function (e) {
ErrorHandlingService.logErrors(e);
})
};
function highlightEntities(results) {
var text = results.text;
var entities = results.entities;
_.forEach(entities, function (entity, i) {
var entity_value = text.substring(entity.start, entity.end);
var color = randomColor({
luminosity: 'light'
});
var borderColor = ColorLuminance(color, -0.3);
$scope.entities[i].backgroundColor = borderColor;
$scope.entities[i].color = color;
var label = document.getElementById('match-text');
setTimeout(function(){ label.innerHTML = label.innerHTML.replace(entity_value, '<span style="background-color:' + color + '; border: 3px solid ' + borderColor + ';" class="highlighted-entities">'+ entity_value + '</span>'); }, 1);
});
}
查看:
<p class="md-subhead">Sentence:</p>
<h3 id="match-text"><span>{{text}}</span></h3>
有谁知道如何在没有超时的情况下做到这一点,因为我认为这是一种非常 hacky 和丑陋的方式来做到这一点?
最佳答案
将您的标签元素传递给 setTimeout 调用的函数:
setTimeout(function(label) {
label.innerHTML = label.innerHTML.replace(entity_value, '<span style="background-color:' + color + '; border: 3px solid ' + borderColor + ';" class="highlighted-entities">' + entity_value + '</span>');
}, 1, label);
关于javascript - elem.innerHTML 仅在设置超时后可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44057809/