Jquery 向HTML添加引导元素的更好方法?
目前,我有一些填充警告的代码,结果是:Jquery 向HTML添加引导元素的更好方法?,jquery,html,twitter-bootstrap,Jquery,Html,Twitter Bootstrap,目前,我有一些填充警告的代码,结果是: $('#alertContainer').html('<div class="alert alert-info alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span>
$('#alertContainer').html('<div class="alert alert-info alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><strong>Warning!</strong> No valid nodes were found for the path object.</div>');
$('#alertContainer').html('×;警告!未找到路径对象的有效节点');
我忍不住认为这是一个可怕的、贫民区化的解决方案,我只是没有正确地使用jQuery来创建这个新元素
那么,有没有更好、更干净的方法 您可以尝试将错误代码放入函数或对象中,以稍微清理脚本并使其更具可读性 功能方法:
function warningCodeCustom(noun) {
var string = '<div class="alert alert-info alert-dismissible" role="alert">';
string += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>';
string += '<strong>Warning!</strong> No valid ' + noun + ' were found for the path object.';
string += '</div>';
return string;
}
我不确定您的代码还能做什么,但
.error()
功能可能有用 不太可能,除非你想在一个变量中创建一个字符串,这个变量比一行代码更容易读取。或者将html放入页面本身,根据条件隐藏/显示。从js字符串向页面添加html并不少见。如果有很多,可以使用模板引擎script@charlietfl哼,这看起来太难看了。但我想这很好,只是希望有更好的解决方案。有趣的是,我在项目的另一部分有这个解决方案,但只用于解析很长的条目(模式->引导选项卡->表格->数据)。我希望有一个更好的解决方案,但如果其他人不出现,我会接受这是最好的解决方案。干杯
window.MyError = window.MyError || {};
MyError.Toolbox = MyError.Toolbox || {
self : this,
init : function() {
//trigger the warning code bind
self.warningCodeBind();
},
warningCodeBind : function() {
//if there are no items on the page add content to our alert container
if(!jQuery('.validNodes, .orOtherNodes').length) {
jQuery('#alertContainer').html(self.warningCodeCustom());
}
},
warningCodeCustom : function(noun) {
var string = '<div class="alert alert-info alert-dismissible" role="alert">';
string += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>';
string += '<strong>Warning!</strong> No valid ' + noun + ' were found for the path object.';
string += '</div>';
return string;
}
};
jQuery(window).load( function() {
MyError.Toolbox.init();
});