简体   繁体   English

Javascript加载具有自己数据的元素后更改href

[英]Change href after Javascript loads elements with its own data

I am using Facebook Embedded posts on my website, and I am trying to change a specific attribute, but failing. 我在网站上使用Facebook Embedded帖子,并且尝试更改特定属性,但失败。

    <a class="_6j_ _5cix" data-ft="{&quot;tn&quot;:&quot;J&quot;}" href="/sharer.php?s=2&amp;appid=2305272732&amp;p%5B0%5D=191027189287&amp;p%5B1%5D=1073742637&amp;share_source_type=unknown" target="_blank" title="Share this item" data-reactid=".r[3suu5].[1].[2]"><i class="_6k1 _528f" data-reactid=".r[3suu5].[1].[2].[0]"></i><span data-reactid=".r[3suu5].[1].[2].[1]">Share</span></a>

So first of all, I need to know how to access that class name. 所以首先,我需要知道如何访问该类名。 The attribute I am trying to change is the href. 我要更改的属性是href。 I also would like to remove "data-reactid=".r[3suu5].[1].[2]" as this is affecting how it works. 我也想删除“ data-reactid =“。r [3suu5]。[1]。[2]”,因为这会影响它的工作方式。

I think I know the code to use to change/remove attributes, the problem I think is I am running it too early as nothing changes. 我想我知道用于更改/删除属性的代码,我想的问题是我现在运行得太早了,因为没有任何变化。 Also, I can go on to Javascript console on google chrome and delete/change things and it works perfectly, I just need it to happen automatically. 另外,我可以转到Google chrome上的Javascript控制台并删除/更改内容,它可以完美运行,我只需要它自动发生即可。

Thanks, Gavin. 谢谢,加文。

What do you need to access the class for? 您需要访问什么课程? There are a multitude of ways to do the things that you want to do, and here are some examples. 有多种方法可以完成您想做的事情,下面是一些示例。 If you elaborate on specifically what your goal is, then that can help narrow down some of the potential solutions. 如果您详细说明您的目标是什么,那么可以帮助您缩小某些潜在解决方案的范围。

This will access the class, remove the attribute data-reactid, and change the href 这将访问该类,删除属性data-reactid,并更改href

myFunction('a','whatever-link.html'); 

function myFunction(el,href) {
    var el = $(el),
        //accesses the class
        currentClass = el.attr('class');

    el.removeAttr('data-reactid');
    el.attr('href',href);
}

OR, this puts everything in a click event 或,这会将所有内容置于点击事件中

$('a').click(function() {
     var currentClass = $(this).attr('class');

     $(this).removeAttr('data-reactid');
     $(this).attr('href','whatever-link.html');
});

OR, this is just a way to take the class of all links and put them in an array (if you want to do it for whatever reason) 或者,这只是获取所有链接的类并将其放入数组的一种方法(如果您出于任何原因要这样做)

var classes = [];

$('a').each(function() {
    classes.push($(this).attr('class'));  
});

You can also select a link by a class: 您还可以按类别选择链接:

 $('._6j_ _cxwhatever_');

I suggest reading jQuery selector documentation 我建议阅读jQuery选择器文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM