Small example - use JS / JQ obtain a href URL tag

The initial idea just want to add a click event can jump set window.

Window.location.href = href itself is to add an event which can be resolved. Behind themselves to engage in their own confused.
Here main point is that the use of JS and JQ get a tag href URL, use relatively simple, basic is to make use of it.
Take a look at part of the code html

 <div>
    <a id="demo" href="https://www.baidu.com"></a>
  </div>
  <p id="p">点击跳转到百度</p>

I put a div tag nested inside, after clicking p tag by clicking on the event "Jump to Baidu" button to get the href, after opening the Baidu website through the new window, enter Baidu.

The following codes are used to JS codes and JQ

  // 使用Js获取
    document.querySelector('#p').onclick = function () {
      var ahref = document.querySelector('#demo');
      window.open(ahref);//在新窗口打开
      window.location.href = ahref;//在原来窗口打开
    }


    // 使用JQ获取
    $('#p').click(function () {
      var hreF = $(this).prev().find('#demo').attr('href');
      window.open(hreF);//在新窗口打开
      window.location.href = hreF;//在原来的窗口打开
    })

In fact, there is a way to open a new page in the original window
and the same as window.location.href = hreF
this method is window.location.replace(hreF)
both open a new window in the original window, but the former can return after opening a new window, but the latter will not be returned.

Gangster seeking answers to the question
why do I get back to the address above, use the server window.location.href = hreFcan not open a new window.
But after using this window.location.replace(hreF)you can open a new window of it

Guess you like

Origin www.cnblogs.com/yohe/p/12231564.html