链接<a> tag downloading the default HTML page when condition is not fulfilled

时间:2016-10-30 18:26:29

标签: javascript html

I am facing a weird problem. I have a link tag to download like

     <div class="col-md-4 about-right">
         <ul>
        <h5>Get My Cv</h5>
        <li><span class="glyphicon glyphicon-user"><input type="radio"class="rad" id="radio1" name="optradio"></span>Download In PDF</li>
        <li><span class="glyphicon glyphicon-user"><input type="radio" class="rad" id="radio2" name="optradio"></span>Download In Word Doc</li>
        <li><span class="glyphicon glyphicon-user"><input type="radio" class="rad"id="radio3"name="optradio"></span>Download In HTML</li>
        <center>
        <a href="#" id="cvLink"  download onclick="getCv()">
         <button type="button" class="btn btn-info">Download</button></a> 
        </center>
       </ul> 
       </div> 

Which downloads documents using radio button checked validation.I have also 3 radio button. I change the URL link based on which radio button is clicked and download the documents using JavaScript. But the problem is when any of the radio button is unclicked I want to show an alert and make the link to do nothing.

I tried this by using "# , javaScript:void(0)". it shows the alert but also downloads the main HTML file on which I am working on. I just want the link will do nothing but show the alert only.

My code is something like below

<script>
function getCv() {
    if(document.getElementById('radio1').checked) {
        document.getElementById('cvLink').href = "https://drive.google.com/uc?export=download&id=MZTFCWnRYbnlvclk";
    }   

    else if(document.getElementById('radio2').checked) {
        document.getElementById('cvLink').href = "https://drive.google.com/uc?export=download&id=uK6ct7MZ2N6Ni1qQUFyWXM";
    }
    else if(document.getElementById('radio3').checked) {
     document.getElementById('cvLink').href = "https://drive.google.com/uc?export=download&id=0VDenJqUldud2M";
    }

    else
    {

     alert('Please Select Any Format To Download!!');
    }
  return false;
}
</script>

3 个答案:

答案 0 :(得分:2)

首先,在我们回答您的问题之前,我想花点时间指出您的HTML存在的一些问题:

<div class="col-md-4 about-right">
  <ul>
    <h5>Get My Cv</h5>
    <li><span class="glyphicon glyphicon-user">
      <input type="radio"class="rad" id="radio1" name="optradio"></span>Download In PDF
    </li>
    <li><span class="glyphicon glyphicon-user">
      <input type="radio" class="rad" id="radio2" name="optradio"></span>Download In Word Doc</li>
    <li><span class="glyphicon glyphicon-user">
    <input type="radio" class="rad"id="radio3"name="optradio"></span>Download In HTML</li>
    <center>
      <a href="#" id="cvLink" download onclick="getCv()">
        <button type="button" class="btn btn-info">Download</button>
      </a>
    </center>
  </ul>
</div>

所以,第一个问题是重复两次的问题,<ul>(或<ol>)的唯一有效直接子元素是{{1}元素。你在那里的其他人,<li><h5>(更多关于 的片刻)是无效的HTML,它们放在这里。

您可以选择从<center>中删除这些元素,或者您只需将它们包装在父<ul>中,以便DOM结构生效。

此外,我认为自从HTML 4.1以来,<li>元素已被弃用。但是,无论何时被弃用,它仍然被弃用,不应再使用。如果您需要在布局中居中使用CSS来设置文档的表示,HTML应该只定义结构。

此外,我认为这是HTML的最后一个问题,在另一个互动元素(如<center>)中拥有一个互动元素(例如<button>)是无效的HTML。在我的演示中,为了重现您的问题,我只是放弃了<a>元素,因为它没有<button>属性。

也就是说,以下JavaScript是我提出的解决方案,HTML也与JavaScript和CSS一起在代码段中:

download

// a named function to highlight the <input> elements required
// in order to enable the <a> element:
function highlightRequirements(e) {

  // caching the element that initiated the events
  // here the <a> element:
  let clicked = this,

      // retrieving the elements that are required to
      // be chosen amongst before the <a> can be used:
      required = document.querySelectorAll(

        // I store, in the <a> element the attribute:
        // data-required="input[name=optradio]"
        // here we use the HTMLElement.dataset interface
        // to retrieve that selector, which is passed as
        // the argument to document.querySelectorAll:
        clicked.dataset.required
      );

  // if the event type (the event, 'e', is passed automatically
  // from the EventTarget.addEventListener() method) is the
  // 'mouseenter' event:
  if (e.type === 'mouseenter') {

    // if the <a> element has the download attribute set:
    if (clicked.download) {

      // we remove the event-listener bound to that element
      // for both 'mouseenter' and 'mouseleave' events:
      this.removeEventListener('mouseenter', highlightRequirements);
      this.removeEventListener('mouseleave', highlightRequirements);

      // and we iterate over the required elements, using
      // Array.prototype.forEach(), and an Arrow function
      // expression, to remove the 'highlight' class from
      // the parentNode of each required ('req') element:
      required.forEach(req => req.parentNode.classList.remove('highlight'));
    } else {

      // if the <a> element does not have the download property,
      // we iterate over the required elements and add the
      // 'highlight' class-name, in order to trigger the animation
      // defined in the CSS, in order to draw the users' attention:
      required.forEach(req => req.parentNode.classList.add('highlight'));
    }

  // otherwise, if the event was not the 'mouseenter' event (and so
  // must be the 'mouseleave' event):
  } else {

    // we iterate over the required elements, and remove the 'highlight'
    // class-name from their parentNodes:
    required.forEach(req => req.parentNode.classList.remove('highlight'));
  }
}

// a named function, fired by the radio inputs, to
// 'enable' or 'activate' the <a> element:
function linkActivate(e) {

  // we use document.querySelector to retrieve the first
  // - if any - element matching the supplied selector:
  var link = document.querySelector(

    // similarly to above, I stored the selector for the
    // relevant <a> element in the 'data-link' attribute,
    // and retrieve that attribute-value using the
    // HTMLElement.dataset interface:
    this.dataset.link
  );

  // setting the download attribute to 'true':
  link.download = true;

  // retrieving the 'data-downloadfrom'
  // attribute-value from the changed
  // radio input:
  link.href = this.dataset.downloadfrom;

  // adding the 'allowed' class to the
  // <a> element, to show that interaction
  // is now possible:
  link.classList.add('allowed');
}

// selecting all the <input> elements with name="optradio":
let radios = document.querySelectorAll('input[name=optradio]'),

    // converting that NodeList into an Array, using
    // Array.from():
    radioArray = Array.from(radios),

  // retrieving the <a> element using
  link = document.querySelector('#cvLink');

// iterating over the Array of radio-inputs using
// Array.prototype.forEach() and an Arrow function:
radioArray.forEach(

  // here we bind the linkActivate() function as the
  // event-handler for the 'change' event:
  radio => radio.addEventListener('change', linkActivate)
);

// here we bind the highlightRequirements() function as
// the event-handler for the 'mouseenter' and 'mouseleave'
// events for the <a> element:
link.addEventListener('mouseenter', highlightRequirements);
link.addEventListener('mouseleave', highlightRequirements);
function highlightRequirements(e) {
  let clicked = this,
      required = document.querySelectorAll(clicked.dataset.required);

  if (e.type === 'mouseenter') {

    if (clicked.download) {
      this.removeEventListener('mouseenter', highlightRequirements);
      this.removeEventListener('mouseleave', highlightRequirements);
      required.forEach(req => req.parentNode.classList.remove('highlight'));
    } else {
      required.forEach(req => req.parentNode.classList.add('highlight'));
    }
  } else {
    required.forEach(req => req.parentNode.classList.remove('highlight'));
  }
}

function linkActivate(e) {
  let link = document.querySelector(this.dataset.link);

  link.download = true;
  link.href = this.dataset.downloadfrom;
  link.classList.add('allowed');
}

let radios = document.querySelectorAll('input[name=optradio]'),
    radioArray = Array.from(radios),
    link = document.querySelector('#cvLink');

radioArray.forEach(
  radio => radio.addEventListener('change', linkActivate)
);

link.addEventListener('mouseenter', highlightRequirements);
link.addEventListener('mouseleave', highlightRequirements);
@keyframes highlight {
  0% {
    background-color: transparent;
  }
  75% {
    background-color: limegreen;
  }
  100% {
    background-color: transparent;
  }
}
ul + a {
  display: inline-block;
  text-align: center;
  text-decoration: none;
  margin: 0.5em auto;
}
ul + a {
  color: #66c;
  cursor: no-drop;
  border: 2px solid #66c;
  padding: 0.2em 0.4em;
  border-radius: 0.5em;
  opacity: 0.5;
}
ul + a.allowed {
  opacity: 1;
  cursor: pointer;
}
li span.highlight {
  animation: 3s highlight;
}

JS Fiddle demo

上面的似乎可以工作,虽然我没有正确验证它;它肯定不会在JS Fiddle演示(附件)中抛出任何错误,我认为清楚地表明需要从无线电<div class="col-md-4 about-right"> <ul> <li> <span class="glyphicon glyphicon-user"> <input type="radio"class="rad" id="radio1" name="optradio" data-downloadfrom="https://drive.google.com/uc?export=download&id=MZTFCWnRYbnlvclk" data-link="#cvLink" /> </span>Download In PDF</li> <li> <span class="glyphicon glyphicon-user"> <input type="radio" class="rad" id="radio2" name="optradio" data-downloadfrom="https://drive.google.com/uc?export=download&id=uK6ct7MZ2N6Ni1qQUFyWXM" data-link="#cvLink" /> </span>Download In Word Doc </li> <li> <span class="glyphicon glyphicon-user"> <input type="radio" class="rad" id="radio3" name="optradio" data-downloadfrom="https://drive.google.com/uc?export=download&id=0VDenJqUldud2M" data-link="#cvLink" /> </span>Download In HTML </li> </ul> <a href="#" id="cvLink" data-required="input[name=optradio]">Download CV </a> </div>元素中进行选择。

似乎是<input>属性表示下载是在执行您通过download内联事件处理程序附加的函数之前启动的(这是一个突兀的JavaScript,这就是为什么我完全用JavaScript绑定我的演示中的事件,虽然我确实将大量数据绑定到HTML中的元素),在这个尝试的解决方案中我删除了onclick属性并且只添加一旦选择了其中一个无线电,就可以通过JavaScript。

答案 1 :(得分:1)

仅使getCv函数返回false是不够的。您需要将返回false写入onclick本身,或者在onclick本身内联返回getCv函数调用的结果:

<a href="#" id="cvLink"  download onclick="return getCv();">

此外,getCv函数的返回值应取决于您是否希望执行链接:

function getCv() {
    if(document.getElementById('radio1').checked) {
        document.getElementById('cvLink').href = "https://drive.google.com/uc?export=download&id=MZTFCWnRYbnlvclk";
        return true;
    }   

    else if(document.getElementById('radio2').checked) {
        document.getElementById('cvLink').href = "https://drive.google.com/uc?export=download&id=uK6ct7MZ2N6Ni1qQUFyWXM";
        return true;
    }
    else if(document.getElementById('radio3').checked) {
     document.getElementById('cvLink').href = "https://drive.google.com/uc?export=download&id=0VDenJqUldud2M";
        return true;
    }

    else
    {
        alert('Please Select Any Format To Download!!');
        return false;
    }
}

答案 2 :(得分:-1)

你应该添加一个“return false;”语句到get​​Cv函数的结尾。 这将阻止a执行。