Replace Tag And Keep Attributes
Solution 1:
functionswitchTag(e, toTag) {
var outerHTML = e.outerHTML;
outerHTML = outerHTML.replace(/^<([a-z])(.*?)>(.*?)<\/\1>$/ig, "<" + toTag + "$2>$3</" + toTag + ">");
e.outerHTML = outerHTML;
};
$(".edit").click(function() {
switchTag(this, "span");
});
Solution 2:
As FAngel indicates, style changes are much simpler in this case. I'm going to go ahead and use event delegation instead of .live
in my example because .live
will be removed in later jQuery versions:
$(document).on('click', '.edit', function (e) {
//add inactive class to *this* link
$(this).addClass('inactive-link');
//stop default link behavior, i.e. opening a new page
e.preventDefault();
});
Solution 3:
$(".edit").live("click", function(e){
if(!$(e.target).hasClass("inactive-link")) { //suppose $(this) will work instead of $(e.target), but do not remember for sure
$(".edit").addClass("inactive-link");// after this is done - this function will not execute anymore for .edit elements because of previouse if statement//code to start editing
}
});
Just check if clicked element has class inactive-link. And remove it after editing is done.
Basically, there is no "disable" feature for links. But you can unbind event handlers while in edit mode, or check if links has some class, like in my code above.
Also, please note that live is deprecated and you should better use .on
(if you have some latest jQuery, v1.7 and higher). Here you can find how to replace live
with on
Solution 4:
// Replacement Tagvar replacementTag = 'span';
$('a').each(function() {
var outer = this.outerHTML;
// Replace opening tagvar regex = newRegExp('<' + this.tagName, 'i');
var newTag = outer.replace(regex, '<' + replacementTag);
// Replace closing tag
regex = newRegExp('</' + this.tagName, 'i');
newTag = newTag.replace(regex, '</' + replacementTag);
$(this).replaceWith(newTag);
});
Solution 5:
I would use two containers : links
and edit-links
When edit button is pressed, I would populate div edit-links
with all the <a>
tags from container links converted to <span>
When save button is pressed, I would re-create all the <a>
tags in the links
container.
$('#myButtonEdit').click(function(){
$('#links').hide();
$('#edit-links').empty();
//loop on all <a> tags to create <span> in edit-links div
$('a').each(function(){
$('#edit-links').append('<span id="'+this.id+'" class="'+$(this).attr('class')+'">'+$(this).attr('href')+'</span>');
});
});
$('#myButtonSave').click(function(){
$('#edit-links').hide();
$('#links').empty();
//loop on all <span> tags to create <a> in links container
$('#edit-links span').each(function(){
$('#links').append('<a id="'+this.id+'" class="'+$(this).attr('class')+'" href="'+$(this).html()+'">'+$(this).html()+'</span>');
});
});
Post a Comment for "Replace Tag And Keep Attributes"