繁体   English   中英

查看渲染-bone.js

[英]view render - backbone.js

我如何在骨干<p><h3>fgfdgdfg</h3></p>结果中取得此结果<p><h3>fgfdgdfg</h3></p>

var TodoView = Backbone.View.extend({
    el:'p',
    render: function () {
        $('body').append(this.$el.html("<h3>fgfdgdfg</h3>"));
    }
});

var todoView = new TodoView();
todoView.render();

使用tagName代替el
编辑以修复错误的html, 谢谢@muistooshort 只需完全删除<p>

var TodoView = Backbone.View.extend({

    tagName:'h3',
    render: function () {
        $('body').append(this.$el.html("fgfdgdfg"));
    }

});

var todoView = new TodoView();
todoView.render();

如果要使用视图的现有DOM元素,则设置el 设置tagName告诉Backbone为视图的根生成一个“ h3”元素。

您也可以这样做(我更喜欢这种方式;避免设置'el'):

var TodoView = Backbone.View.extend({

    tagName:'h3',
    render: function () {
        this.$el.html("fgfdgdfg");
        return this;
    }

});

// view is more reusable now, since it doesn't have the 'body' part in render.
// So, another instance could be rendered and added to the page somewhere else.
var todoView = new TodoView();
$('body').append(todoView.render().el);
var todoView2 = new TodoView();
$('body').append(todoView2.render().el);

如果您的html已经具有要用于视图的'h3'元素,则可以执行以下操作:

// assuming this html on the page already:
// <body><h3></h3></body>
var TodoView = Backbone.View.extend({

    // setting 'el' tells backbone to use the existing <h3>.
    // You probably would want to use an id rather than 'h3' though.
    el:'h3',
    render: function () {
        this.$el.html("fgfdgdfg");
        return this;
    }

});

var todoView = new TodoView();
todoView.render();

您可能不能这样做,因为<p><h3>fgfdgdfg</h3></p>不是有效的HTML,浏览器经常会尝试更正无效的HTML。

优良的<p>规范

允许的内容

短语内容

措辞的内容是:

措辞内容

由与普通字符数据混合的短语组成

普通字符数据或多或少是纯文本,没有标记,因此<h3>不会在其中。 短语元素是简单的内容,例如<a><b><img> ,...,并且其中也没有<h3>

如果要获得一致的结果,则必须修复HTML。 然后,一旦您想到了有效的HTML, Paul的建议就应该完成事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM