Reputation: 16793
I have this code which I need to set a unique 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);
});
What I want to happen, is that each time the each
iterates over the <input>
, it updates the title
value in the tmpImg
string. I know I could separate the img HTML like below, although I think this would get messy when I need to reuse the image later down the script.
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 + '" />');
});
Upvotes: 1
Views: 263
Reputation: 344575
This is how I'd do it, for what it's worth:
$(this).find("tr td input").each(function(){
$('<img/>', {
src: "/admin/icons/cross.png",
title: this.value
}).insertBefore(this).next().hide();
});
Upvotes: 1
Reputation: 106027
These string replacement solutions are nuts. Just make a copy of the element and set the attribute on it directly.
var tmpImg = $( '<img src="/admin/icons/cross.png" />' );
$(this).find( "tr td input" ).each(function() {
$(this).hide().before( tmpImg.clone().attr( 'title', this.value ) );
});
Upvotes: 3
Reputation: 1074295
You can put some kind of placeholder token in the string, then use 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")));
});
Side note: $(this).attr('value')
is usually better written this.value
or $(this).val()
.
Upvotes: 0
Reputation: 66389
Change the variable to sort of template:
var tmpImg = '<img src="/admin/icons/cross.png" title="$title" />';
Then replace it with the input value:
$(this).hide().before($(tmpImg.replace("$title", this.value)));
The above has minimal changes to original code, the better jQuery way though is this:
$(this).hide().before($("<img />").attr("src", "/admin/icons/cross.png").attr("title", this.value));
Upvotes: 2