如何将变量插入变量字符串?

时间:2012-01-23 09:53:42

标签: javascript jquery

我有这个代码,我需要设置一个唯一的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>时,它都会更新title字符串中的tmpImg值。我知道我可以像下面那样分离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 + '" />');
});

4 个答案:

答案 0 :(得分: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 ) );
});

答案 1 :(得分:2)

将变量更改为模板排序:

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

然后用输入值替换它:

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

上面对原始代码的修改很少,但更好的jQuery方式是:

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

答案 2 :(得分:1)

我就是这样做的,因为它值得:

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

答案 3 :(得分: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()

相关问题