Я бы предложил:
// retrieving the the elements matching the 'a.share' CSS selector:
$('a.share')
// using the on() method to bind the anonymous function as the
// 'click' event-handler:
.on('click', function(event) {
// preventing the default behaviour of the clicked <a> element:
event.preventDefault();
// caching the clicked <a> element:
let clicked = $(this);
// retrieving the elements matching the supplied CSS selector,
// this could be simplified depending on the presence of other
// 'a.fb' elements that you wish, or don't wish, to affect with
// the same functionality:
$('div.sharewpopup a.fb')
// here we update the 'href' attribute of the found element(s),
// using the .attr() method:
.attr('href',
// we update it to the result of the next expression; here
// find the closest (ancestor) '.post' element:
clicked.closest('.post')
// from there we find the descendant elements that match
// the supplied 'h2 > a' CSS selector:
.find('h2 > a')
// and retrieve the 'href' attribute-value of the first
// element in the returned correction, using the .attr()
// method as the getter:
.attr('href'));
});
$('a.share').on('click', function(event) {
event.preventDefault();
let clicked = $(this);
$('div.sharewpopup a.fb').attr('href', clicked.closest('.post').find('h2 > a').attr('href'));
});
a.fb::after {
content: ' (' attr(href) ')';
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div class='sharewpopup'>
<a class='fb'>Share to Facebook</a>
</div>
<!--POST 1-->
<div class='post'>
<h2 class='title'><a href='#LINK1'>POST TITLE 1</a></h2>
<a class='share' href='#'>Share</a>
</div>
<!--POST 2-->
<div class='post'>
<h2 class='title'><a href='#LINK2'>POST TITLE 2</a></h2>
<a class='share' href='#'>Share</a>
</div>
Это также может быть сделано довольно просто с простым JavaScript:
// defining a named function to handle the copying of attribute,
// this takes one argument - an Event object, provided automagically
// by the EventTarget.addEventListener() method (later):
const hrefToShare = (event) => {
// again, we prevent the default action of the clicked <a> element:
event.preventDefault();
// here we find, and cache, the first (if any) 'a.fb' element
// that matches the supplied CSS selector:
let shareLink = document.querySelector('div.sharewpopup a.fb'),
// we cache the clicked <a> element, via the 'target'
// property of the Event object:
clicked = event.target,
// here navigate from the clicked <a> to the
toShare = clicked
// closest (ancestor) element matching the '.post' CSS
// selector:
.closest('.post')
// from that element we find the first descendant element
// using Element.querySelector that matches the supplied
// CSS selector:
.querySelector('h2 > a');
// then we update the href property (not the attribute) of the
// shareLink element (the a.fb) to be equal to the href property
// (not the attribute) of the toShare ('LINK1','LINK2') element:
shareLink.href = toShare.href
}
// here we retrieve a nodeList of the elements that match the
// 'a.share' CSS selector:
let shareLinks = document.querySelectorAll('a.share');
// here we iterate over those found nodes, and use an Arrow function
// to add an event-listener to each in turn, supplying the named
// hrefToShare() function (note the deliberate lack of parentheses)
// as the event-handler for the 'click' event:
shareLinks.forEach(
// the 'share' argument is a reference to the current Node
// of the NodeList over which we're iterating:
(share) => share.addEventListener('click', hrefToShare)
);
const hrefToShare = (event) => {
event.preventDefault();
let shareLink = document.querySelector('div.sharewpopup a.fb'),
clicked = event.target,
toShare = clicked
.closest('.post')
.querySelector('h2 > a');
shareLink.href = toShare.getAttribute('href');
}
let shareLinks = document.querySelectorAll('a.share');
shareLinks.forEach(
(share) => share.addEventListener('click', hrefToShare)
);
a.fb::after {
content: ' (' attr(href) ')';
}
<div class='sharewpopup'>
<a class='fb'>Share to Facebook</a>
</div>
<!--POST 1-->
<div class='post'>
<h2 class='title'><a href='#LINK1'>POST TITLE 1</a></h2>
<a class='share' href='#'>Share</a>
</div>
<!--POST 2-->
<div class='post'>
<h2 class='title'><a href='#LINK2'>POST TITLE 2</a></h2>
<a class='share' href='#'>Share</a>
</div>
Выше я использовал следующую строку JavaScript:
shareLink.href = toShare.href
это скопировать href
свойство одного <a>
элемента к другому, вместо этого я мог бы использовать:
shareLink.setAttribute('href', toShare.getAttribute('href'));
или:
shareLink.setAttribute('href', toShare.href);
, эти две строки приводят практически к одному и тому же, иобновит атрибут href
, чтобы он был правильным; первый скопирует атрибут href
, а второй скопирует свойство href
из элемента toShare
.Любая из них приведет к работающей ссылке (при условии, что ссылка toShare
является функциональной и не зависит от последующих манипуляций JavaScript).
Что (потенциально) не будет работать:
shareLink.href = toShare.getAttribute('href');
Причина в том, что атрибут href
может быть относительным URL-адресом, который анализируется браузером, когда пользователь пытается перейти по ссылке, тогда как свойство href
является абсолютным URL-адресом (полученным из относительного, корневого-относительногоили абсолютный URL, найденный в атрибуте href
).Итак, свойство href
является или должно быть абсолютным URL.
Ссылки: