2017-04-07 161 views
2

这是可能的在angularjs/jquery/javascript?如何动态更改html标签?

<div ng-init="font='h2'"> 
    <h1> h1 is this size </h1> 
    <{{font}}> this is a {{font}}</{{font}}> 
</div> 

如何动态更改html标签? 预先感谢您。

ps:我已经试过这段代码,但没有成功。

+1

这当然是可能的。你究竟需要改变什么 –

+0

他的意思是把标签从''改为''。 – Feathercrown

+1

您总是可以使用jQuery使用新标记创建一个新元素,设置其.innerHTML,然后用新元素替换旧元素。现场示例:https://jsfiddle.net/j5077qjn/(提示:jQuery是JavaScript) –

回答

1

您可以用自定义指令做到这一点:

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>

1

至于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>

1

这里有一个简单的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>

1

与JavaScript和JQuery的当然是可能的。 。

的JavaScript:使用的document.getElementById( “身份识别码”)outerHTML

JQuery的:参考见本 - http://api.jquery.com/insertAfter/#selector

这似乎是一个不好的做法,通过JavaScript修改DOM元素(虽然可能)

如果采用了棱角分明,我会建议使用NG-如果或组合NG-如果和NG-包括如果你想有条件地加载了一个新的视图/ HTML