用jquery向html中动态添加input,然后希望给这些input绑定keyup事件,在input中输入的同时同步更新页面上的文字内容。
开始用的是,其中business logic比较旧,与后面的代码不一致。
//Related to content
//Real time update of content
$('.text-content').keyup(function(){
if(textElement !== null){
if($('#text-effect').val() === null || $('#text-effect').val() === 'plain'){
textElement.text($(this).val());
}
else{
var svg = getTextEffect(createUrl());
refreshText(svg, GTYPE);
}
}
});
最初以为keyup只能用在id上,不能用在class上。后来发现不是这样。没反应是因为这些input是动态生成的,jquery不能动态把这些事件绑定到新生成的元素上。具体解释见:
http://www.cnblogs.com/wmmang-blog/archive/2013/03/13/2818092.html
http://stackoverflow.com/a/12830014/2177408
所以改用on。具体代码如下:
$('.text-editor-wrapper').on('keyup', '.text-content', function(){
var index = $(this).parent().find('.text-index').text() - 1,
textElement = textList[index];
if($(textElement).prop('tagName') === 'textPath' || $(textElement).prop('tagName') === 'tspan'){
$(textElement).text($(this).val());
}
else{
textElement.nodeValue = $(this).val();
}
});