【问题标题】:Change href of dynamicly created link更改动态创建链接的href
【发布时间】:2016-11-10 19:59:07
【问题描述】:

我有一个带有 Visual Composer 插件的 Wordpress 站点 http://gambit.co/test,它允许我在 WYSIWYG 模式下创建页面。它创建的所有内容都加载了 ajax 和 javascript。我有一些不错的媒体网格部分,但我无法将特定链接分配给方块。他们都是与他们的图像相关的缩影。

我尝试用 jQuery 替换他们的链接

jQuery(document).ready( function($) {
$("a[href='http://gambit.co/test/wp-content/uploads/2016/07/600_wynajem.jpg']").attr('href', 'http://www.google.com/');

});

但我不能正常工作,因为脚本运行时没有 HTML 内容。我将脚本移到页面底部,就在关闭 BODY 标记之前,但 id 不起作用。我用 .attr 和 .prop 都试过了。我该怎么办?

【问题讨论】:

  • content is loaded with ajax and javascript; 这是否意味着它被您使用 $.ajax 编写的代码加载;还是别的什么?

标签: jquery replace href dynamically-generated visual-composer


【解决方案1】:

试试看DOMNodeInserted

这样你就可以写出这样的东西:

// as soon as a new anchor tag is added to the dom and
// the href value of this element is......
$(document).on('DOMNodeInserted', 'a[href="http://gambit.co/test/wp-content/uploads/2016/07/600_wynajem.jpg"]', function(e) {
  this.href = 'http://www.google.com/';
  
  this.textContent = 'http://www.google.com/';
});


$(function () {
  $('#btn').on('click', function(e) {
    $('body').append('<a href="http://gambit.co/test/wp-content/uploads/2016/07/600_wynajem.jpg">My sample</a>');
  })
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

<button id="btn">Add link</button>

【讨论】:

    猜你喜欢
    • 2017-01-05
    • 1970-01-01
    • 2021-08-15
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 2017-04-02
    • 2011-06-16
    相关资源
    最近更新 更多