這是可能的在angularjs/jquery/javascript?如何動態更改html標籤?
<div ng-init="font='h2'">
<h1> h1 is this size </h1>
<{{font}}> this is a {{font}}</{{font}}>
</div>
如何動態更改html標籤? 預先感謝您。
ps:我已經試過這段代碼,但沒有成功。
這是可能的在angularjs/jquery/javascript?如何動態更改html標籤?
<div ng-init="font='h2'">
<h1> h1 is this size </h1>
<{{font}}> this is a {{font}}</{{font}}>
</div>
如何動態更改html標籤? 預先感謝您。
ps:我已經試過這段代碼,但沒有成功。
您可以用自定義指令做到這一點:
var app = angular.module('app', []);
app.controller('MyController', ['$scope', '$timeout', function($scope, $timeout) {
$scope.font = 'h2';
$timeout(function() {
$scope.font = 'h3';
$timeout(function() {
$scope.font = 'h4';
$timeout(function() {
$scope.font = 'h5';
}, 1000);
}, 1000);
}, 1000);
}]);
app.directive('font', function($interpolate, $compile) {
return {
restrict: 'E',
scope: false,
link: function($scope, $element, $attr) {
var content = $element.html();
$scope.$watch('font', function(newVal) {
$element.contents().remove();
var tag = $interpolate('<{{font}}>{{content}}</{{font}}>')
({
font: $scope.font,
content: content
});
var e = angular.element(tag);
$element.append($compile(e)($scope));
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-init="font='h2'" ng-app="app" ng-controller="MyController">
<h1> h1 is this size </h1>
<font>This is a {{font}}</font>
</div>
至於jQuery的你可以使用replaceWith()方法。您只需在點擊事件期間保留文本/類。
$(function() {
$('.button').on('click', function() {
var $span = $('.span');
var lvl = $(this).data('lvl');
$span.replaceWith(`<${lvl} class="span">${$span.text()} as an ${lvl}<${lvl}>`);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" data-lvl="h2">Change to h2</button>
<button class="button" data-lvl="h5">Change to h5</button>
<div ng-init="font='h2'">
<h1>h1 is this size </h1>
<span class="span">this is a font</span>
</div>
這裏有一個簡單的JavaScript解決方案:
var i=0;
setInterval(function()
{
document.getElementById("changeable").outerHTML = "<h" + (i+1) + " id=\"changeable\">" + document.getElementById("changeable").innerHTML + "</h" + (i+1) + ">";
i++;
if(i>=5){
i=0;
}
},1000);
<div>
<h1> h1 is this size </h1>
<h2 id="changeable"> this is a header tag</h2>
</div>
與JavaScript和JQuery的當然是可能的。 。
的JavaScript:使用的document.getElementById( 「身份識別碼」)outerHTML
JQuery的:參考見本 - http://api.jquery.com/insertAfter/#selector
這似乎是一個不好的做法,通過JavaScript修改DOM元素(雖然可能)
如果採用了棱角分明,我會建議使用NG-如果或組合NG-如果和NG-包括如果你想有條件地加載了一個新的視圖/ HTML
這當然是可能的。你究竟需要改變什麼 –
他的意思是把標籤從''改爲''。 – Feathercrown
您總是可以使用jQuery使用新標記創建一個新元素,設置其.innerHTML,然後用新元素替換舊元素。現場示例:https://jsfiddle.net/j5077qjn/(提示:jQuery是JavaScript) –