问题
I bulk replace html in many divs with replaceWith. After replacing I am using jTruncate to truncate the texts. However it doesn't work, because at the time of execution, replaceWith is not done.
I tried the callback trick (How do I extend jQuery's replaceWith function to accept a callback function?) but didn't work.
Any ideas?
$(".hotel_info").each(function () {
var div;
div = $(this);
div.replaceWith(data);
truncInfo(div);
});
function truncInfo(div) {
div.jTruncate({
length: 100,
minTrail: 100,
moreText: '[more...]',
lessText: '[less...]',
ellipsisText: '...',
moreAni: 'fast',
lessAni: 'fast'
});
}
回答1:
Ok, found the solution thanks to this post: jQuery replaceWith find new element
It seems that after replace with, the object is removed from the DOM, so a new one is created. So, I had to change the code like this:
$(".hotel_info").each(function () {
var div; var div2;
div = $(this);
div2 = div.replaceWithPush(data);
truncInfo(div2);
});
$.fn.replaceWithPush = function (a) {
var $a = $(a);
this.replaceWith($a);
return $a;
};
Thank you all for your time!
回答2:
Unlike jQuery functions such as .find()
, .replaceWith()
doesn't update the set of elements (which makes up the jQuery object itself).
This means that upon removal, you're left with old references; the trick here is to keep a reference of what you replace the element(s) with.
In your case, you could do it differently, though:
$(".hotel_info").replaceWith(function () {
return truncInfo(this);
});
Be sure to make truncInfo
return the results of calling jTruncate()
:
function truncInfo(div)
{
return div.jTruncate({
length: 100,
minTrail: 100,
moreText: '[more...]',
lessText: '[less...]',
ellipsisText: '...',
moreAni: 'fast',
lessAni: 'fast'
});
}
回答3:
To just try with the async and sync part you can use setTimeout function.
setTimeout(function(){truncInfo(div)}, 3000);
This would wait for 3 seconds before calling the truncInfo function.
3 seconds would be enough for the replaceWith function to complete its processing. You can extend the time as per your choice and check.
This is not an ideal practice but may work in some cases.
For more details on setTimeout please check http://www.w3schools.com/jsref/met_win_settimeout.asp
Hope this helps.
来源:https://stackoverflow.com/questions/24429210/jquery-wait-for-replacewith-to-finish-before-executing