2012-01-23 122 views
1

我有这样的代码,我需要设置一个唯一的title如何将变量插入到变量字符串中?

var tmpImg = '<img src="/admin/icons/cross.png" title="' + title + '" />'; 

$(this).find("tr td input").each(function(){ 
    title = $(this).attr("value"); 
    $(this).hide().before(tmpImg); 
}); 

我希望发生的,就是每一次迭代each<input>,它将更新tmpImg字符串title值。我知道我可以像下面那样分开img HTML,但我认为当我需要在后面的脚本中重新使用图像时,这会变得混乱。

var tmpImg = '<img src="/admin/icons/cross.png" title="'; 

$(this).find("tr td input").each(function(){ 
    title = $(this).attr("value"); 
    $(this).hide().before(tmpImg + title + '" />'); 
}); 
+1

我觉得轻度有趣,你拼写单词“变量”两种不同的方式 - 无论是不正确 - [在问题标题](http://stackoverflow.com/posts/8969771/revisions#revbac494ba-2a4a-4d42-987e-d10db9de3e62):-) –

回答

3

这些字符串替换解决方案是坚果。只需制作元素的副本并直接在其上设置属性即可。

var tmpImg = $('<img src="/admin/icons/cross.png" />'); 

$(this).find("tr td input").each(function() { 
    $(this).hide().before(tmpImg.clone().attr('title', this.value)); 
}); 
+0

这看起来像我会作为答案。 –

2

改变变量排序模板:

$(this).hide().before($(tmpImg.replace("$title", this.value))); 

以上具有最小改动原来的代码,更好的jQuery的方法:

var tmpImg = '<img src="/admin/icons/cross.png" title="$title" />'; 

然后利用输入值替换虽然是这样的:

$(this).hide().before($("<img />").attr("src", "/admin/icons/cross.png").attr("title", this.value)); 
0

你可以把某种占位符号的字符串,然后使用replace

var TITLE_TOKEN = '%%TITLE%%'; 
var tmpImg = '<img src="/admin/icons/cross.png" title="' + TITLE_TOKEN + '" />'; 

$(this).find("tr td input").each(function(){ 
    $(this).hide().before(tmpImg.replace(TITLE_TOKEN, $(this).attr("value"))); 
}); 

旁注:$(this).attr('value')通常是更好的书面this.value$(this).val()

1

这是我怎么会做它,因为它的价值:

$(this).find("tr td input").each(function(){ 
    $('<img/>', { 
     src: "/admin/icons/cross.png", 
     title: this.value 
    }).insertBefore(this).next().hide(); 
}); 
相关问题