Как скопировать attibute href в другой элемент "a" [JQUERY] - PullRequest
0 голосов
/ 26 января 2019

Я хочу скопировать атрибут href элемента h2.title a в элемент a.fb, когда я нажимаю a.share.

Но у каждого есть один a.share.

Если я нажму первый a.share, #LINK1 скопирует в a.fb.

Если я нажму второй a.share, #LINK2 также скопирует в a.fb и удалит существующее значение ватрибут href at a.share.

Извините за плохой английский: (* ​​1022 *

Спасибо за помощь мне

<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>

Ответы [ 4 ]

0 голосов
/ 26 января 2019

Вам может не понадобиться jQuery для этого.Простого JS будет достаточно.

Если вы используете HTML-код, который вы упомянули, каждый a.share previousElementSibling будет ближайшим h2.title каждый раз, когда вызывается shareMe.

Внутри него a Элем будет тот, который содержит 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' onclick="javascript:shareMe(this);" href='#'>Share</a>
  </div>

  <!--POST 2-->
  <div class='post'>
    <h2 class='title'><a href='#LINK2'>POST TITLE 2</a></h2>
    <a class='share' onclick="javascript:shareMe(this);" href='#'>Share</a>
  </div>

  <script>
    function shareMe(aElem) {
      var dest = aElem.previousElementSibling.querySelector('a').href;
      document.querySelector('.sharewpopup a').href = dest;
      return false;
    }
  </script>
0 голосов
/ 26 января 2019

Нажмите на ссылку «Поделиться», найдите ее оболочку .post, найдите внутри нее h2 и перейдите по ссылке внутри h2.Теперь возьмите ссылку с этой ссылки и добавьте ее к ссылке .fb.

var $fbLink = $('.sharewpopup .fb');

$('.share').on('click', function(e) {
  e.preventDefault();
  var $linkToShare = $(this).closest('.post').find('.title a');
  $fbLink.attr('href', $linkToShare.attr('href'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></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>
0 голосов
/ 26 января 2019

Два пути

  • использовать eq когда вы хотите скопировать первому одному пользователю
$("a.share").eq(0).attr("href", $(h2.title a).eq(0).attr("href"))

и вторая ель:

$("a.share").eq(1).attr("href", $(h2.title a).eq(1).attr("href"))
  • или просто используйте prev, поскольку .share и h2 находятся в одном поле:
$("a.share").attr("href", this.prev('h2').find("a").attr("href"))

this - это когда вы связываете кнопку envent на a.share

0 голосов
/ 26 января 2019

Я бы предложил:

// 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.

Ссылки:

...