在jQuery中修剪部分链接

时间:2018-01-26 19:37:32

标签: javascript jquery

我试图删除jQuery中链接的开头。我试图注入以下功能,但它不起作用。我究竟做错了什么?

JS

$(function() {
  $('link-active').each(function() {
     $(this).attr('href').remove('http://www.linkplus.com/xQWE=');
     });
});

HTML

<td class="block">
<a class="link-active" 
href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
</td>

7 个答案:

答案 0 :(得分:1)

当您尝试搜索课程时,请使用点(。),$('link-active')应为$('.link-active')
关于.remove():这个将删除DOM的一个元素;在这种情况下不适用。

解决方案:您需要使用.attr()返回并更新代码的href属性,.replace()方法应该有所帮助。

&#13;
&#13;
$(function() {
  $('.link-active').each(function() {
    let href = $(this).attr('href'); //returns href value
    let removableUrl = 'http://www.linkplus.com/xQWE=';
    href = href.replace(removableUrl, ''); //replace the url you don't want with ''
    $(this).attr('href', href); //update href value
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="block">
<a class="link-active" 
href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>
</td>
&#13;
&#13;
&#13;

注意:还有其他方法来分隔您不想要的网址(如果网址保持相同格式),请检查:
.substring()href = href.substring(removableUrl.length);
.split()href = href.split('=')[1];
带有正则表达式的 .replace():href = href.replace(/.*\=/,'');

答案 1 :(得分:0)

$('link-active')修改为$('.link-active')

答案 2 :(得分:0)

首先,在jQuery中表示一个类时尝试使用点表示法。

$(function() {
  $('.link-active').each(function() {
     $(this).attr('href').remove('http://www.linkplus.com/xQWE=');
     });
});

答案 3 :(得分:0)

使用attr这样的方法很方便:

$(function() {
  $('.link-active').attr('href', function(i, href) {
    return href.replace('http://www.linkplus.com/xQWE=', '');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="link-active" href="http://www.linkplus.com/xQWE=http://www.example.com">Get</a>

答案 4 :(得分:0)

将第3行的代码更改为

$(this).attr('href', $(this).attr('href').replace('http://www.linkplus.com/xQWE=', ''));

完整代码应为

$(function() {
  $('link-active').each(function() {
     $(this).attr('href', $(this).attr('href').replace('http://www.linkplus.com/xQWE=', ''));
     });
});

答案 5 :(得分:0)

这里没有正确使用

remove,因为该方法旨在从DOM中删除元素并接受选择器字符串作为其参数。

尝试这样的事情:

$(function() {
  $('.link-active').each(function() {
     var href = $(this).attr('href');
     var strToReplace = 'http://www.linkplus.com/xQWE=';
     $(this).attr('href', href.replace(strToReplace, ""));
  });
});

上面我们使用replace用空字符串替换链接的开头。

答案 6 :(得分:0)

你必须得到字符串,替换它然后再设置它。

这样的事情:

$(function() {
    $('link-active').each(function() {
    replacement = 'http://www.linkplus.com/xQWE=';
    url = $(this).attr('href');
    $(this).attr('href', url.replace(replacement, ''));
    });
});