I开发者_如何转开发 want to disable all links within a div and replace it with the content that was there.
i.e.
<div><a href="/blah.html">My super link</a></div>
to
<div>My super link</div>
Thanks
You can do it using .replacewith()
and a function, like this:
$("div a").replaceWith(function() { return $(this).text(); });
You can see a quick demo here
Hmm - mine is similar to the other quicker-typists' answers, but I would have thought html()
would have been what you wanted to use:
$('div a').each(function() {
$(this).replaceWith($(this).html());
});
I know this question is old, but I accomplished this by doing the following:
1 - selecting all anchors that I wanted to disable
2 - removing all events associated with the anchor
3 - replace the href attribute value with a #
4 - add a click event to the anchor which does nothing
The below code sample below is cut from my plugin. The plugin also has code to
enable the anchor back again. It may give you ideas.
You can also download my plugin at ( http://www.dougestep.com/dme/jquery-disabler-widget ) and use it or cut out what you need from it.
$('a').each(function(e) {
// disable events on anchor
this._disableEvents($(this));
// save off the HREF value
var href = inp.attr("href");
if (href != undefined) {
// save the HREF attribute value and remove the value
inp.data(dataAnchorHref, href);
inp.attr("href", "#");
}
// override the click event for the anchor
inp.on("click", function(e) {
e.preventDefault();
});
// decorate the anchor with a disabled look
inp.addClass('ui-state-disabled');
});
_disableEvents : function(inp) {
var de = $.Event("disableEvents");
this._trigger("disableEvents", de, inp);
if (de.isDefaultPrevented()) { return; }
var widgetEventPrefix = this.widgetEventPrefix;
// jQuery adds an "events" data attribute on the element when events are registered
var events = inp.data("events");
if (events != undefined) {
var savedEvents = [];
// loop through each event found on the element...
$.each(events, function(eventName, handlers) {
$.each(handlers, function(index) {
var handler = handlers[index];
if (handler != undefined) {
// save the event and handler
var eventObj = {
'eventName' : eventName,
'handler' : handler
};
if (eventName.indexOf(widgetEventPrefix) < 0) {
// unbinding a non widget event
savedEvents.push(eventObj);
inp.unbind(eventName);
}
} });
});
// store the saved events as a data attribute on the element
inp.data(dataSavedEvents, savedEvents);
}
}
精彩评论