用DOM元素替换字符串 [英] Replace string with DOM element

查看:70
本文介绍了用DOM元素替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,我喜欢用DOM元素替换某些部分:

I have a string in which I like to replace some part with DOM element:

var mainStr = 'akedf abc dde';

var span = document.createElement('span');
span.id = 'word';
span.innerHTML = '123';
$(span).click(this.touchHandler);

var n = mainStr.replace('abc',span.innerHTML);

var htmlObject = document.createElement('div');
htmlObject.innerHTML = n;


touchHandler:function(e){
    console.log('log something')
},

此代码不起作用,'abc'字符串替换为'123',但touchHandler不起作用。

this code does not work, the 'abc' string is replaced with '123' but the touchHandler does not work.

代码在Backbone.js中

The code is in Backbone.js

我有什么方法可以做到这一点吗?

Is there some way that I can do this?

推荐答案

不喜欢这样。将span插入文档的方式( var n = ... )将span视为dumb HTML并将其留给浏览器以实际创建元素并插入进入DOM;您没有插入自己的 span 元素,因此点击处理程序不起作用。

Not like this. The way you insert the span into the document (var n = ...) treats the span as dumb HTML and leaves it to the browser to actually create the element and insert it into the DOM; your own span element is not inserted, therefore the click handler doesn't work.

您可以附加处理程序以这种方式实际元素:

You can attach the handler to the actual element this way:

var mainStr = 'akedf abc dde';

var span = document.createElement('span');
span.id = 'word';
span.innerHTML = '123';

var n = mainStr.replace('abc',span.innerHTML);

var htmlObject = document.createElement('div');
htmlObject.innerHTML = n; // the browser creates new span element
$(htmlObject).find("span").click(this.touchHandler); // click handler attached

这篇关于用DOM元素替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆