我有一个由核心模块生成的链接(意思是我无法修改代码):
<a id="my-unique-id-1" class="my-link-class" href="/switch off">Switch off</a>
问题是,ID和类在<a>
标记内,并且我没有任何可用的元素包裹在我可以使用的链接中。
单击时,它会执行服务器端所做的操作(请参阅下面的代码),然后返回:
<a id="my-unique-id-1" class="my-link-class it-is-off" href="/switch on">Switch on</a>
我想替换或修改完整的第一个链接。
首先是jQuery脚本:
$(".my-link-class").click(function() {
var current_id = $(this).attr('id');
var link = $(this).attr('href');
$.ajax({url: link, success: function (result) {
//All works fine up to here. The changes are made in server side and returns the new link as the result.
//Following is my problem:
if(result){
$(current_id).replaceWith(result); //the selector is wrong, I know.
}
}
}
我的问题是id(current_id)已经在<a>
标记内。
如何引用标签中的选择器。
我试过了:
$(current_id).replaceWith(result); //nothing happens
$('#' + current_id).replaceWith(result);
$('a#' + current_id).replaceWith(result);
但我得到了最后两个TypeError:Node.appendChild的Argument 1没有实现接口Node。
(我知道我可以做其他事情而不是替换,比如在链接中更改文本和href,但这里的问题是首先找到选择器。)
答案 0 :(得分:0)
您可以使用$(this).replaceWith()
:
$(document).on('click', '.my-link-class', function() {
var html = '<a id="my-unique-id-1" class="my-link-class it-is-off" href="/switch on">Switch on</a>';
$(this).replaceWith(html);
return false;
});
.it-is-off {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="my-unique-id-1" class="my-link-class" href="/switch off">Switch off</a>
答案 1 :(得分:0)
我认为这里发生了两件事。
您正在尝试使用ID来替换元素,这样可以更容易地保留对要替换的DOM元素的引用,而不是找到它两次。
您正在将事件绑定到您正尝试替换的锚标记。一旦你更换它,事件就会消失。避免此问题的方法是将事件绑定到不会更改的事件。这可能是您要替换的元素正上方的元素,或者它可以是更高的元素,如body
元素。
这是解决这两个问题的可能解决方案。我编写了一个名为simulatedAjax
的函数,以便了解我认为你所说的后端代码正在做什么。它遵循与使用configurationObject, callback(result)
签名的jQuery $ .get相同的想法。
function simulatedAjax(config, done){
var onOffText = (config.url === "on" ? "off" : "on");
done('<a href="'+onOffText+'" id="custom-thing" class="custom-link">Switch '+ onOffText +'</a>');
}
现在是您的客户代码
$(function(){
// Bind the click to the body element, but with a delegate to your link class .custom-link
$('body').on('click', '.custom-link', function(e){
// Store a reference to the A tag, name is irrelevant but self is easy to understand
var self = this;
// Keep the page from actually navigating to the href
e.preventDefault();
//Replace with real jQuery $.get or $.ajax with configuration
simulatedAjax({
url: $(this).attr('href')
}, function(resultHTML){
// Since we stored a reference to the original in the self variable, we can just replace it here. Note that if we tried to use `this` here, it wouldn't refer to the right `this`
$(self).replaceWith(resultHTML);
});
});
});
您可以在此JSFiddle http://jsfiddle.net/x83vfmuw/
中看到此代码示例希望这有帮助!