如果用户选中“同意条款”框或单选按钮,则允许用户从链接下载文件

时间:2015-02-11 19:59:36

标签: javascript jquery download

我想设置类似于the one here on Oracle's website的文件下载页面。

如何重新创建此内容?

我不熟悉编写javascript,但我发现使用javascript来显示表格并控制弹出窗口,并在选择“同意条款”单选按钮后替换链接。他们正在使用此代码:

// Dynamically generated download page for OTN. 
// Aurelio Garcia-Ribeyro, 2012-05-21, based off of pre-existing code for OTN license acceptance

// Only the 'downloads' array should need to be modified, unless the look/feel needs to be changed in the body at the bottom

// 'downloads' is an array of releases, using the CDS part number as the key for each release. Each release is also an array of meta-data for that release. Finally, there is a 3rd nested array of files to be offered in the release.

// downloads[product][path] will assumed to be the path for each file. NOT YET IMPLEMENTED: Unless downloads[product]['files']['path'] is defined. 
// The filename will assumed to be the key for path from downloads[product]['files']. NOT YET IMPLEMENTED: Unless downloads[product]['files']['filename'] is defined. 

var page_title = "Java SE Development Kit 8 Downloads";
var page_blurb = '<p>Thank you for downloading this release of the Java<sup>TM</sup> Platform, Standard Edition Development Kit (JDK<sup>TM</sup>). The JDK is a development environment for building applications, applets, and components using the Java programming language.</p> <p>The JDK includes tools useful for developing and testing programs written in the Java programming language and running on the Java platform.<br></p><div>See also:</div> <div> <div> <ul> <li><a href="http://myprofile.oracle.com/">Java Developer Newsletter</a>&nbsp;(tick the checkbox under Subscription Center &gt; Oracle Technology News)</li> <li><a href="http://events.oracle.com/search/search?start=&amp;pageHitCount=10&amp;group=Events&amp;keyword=java">Java Developer Day hands-on workshops (free) and other events</a></li> <li><a href="http://www.oracle.com/technetwork/java/javamagazine/index.html">Java Magazine</a></li> </ul> JDK MD5 <a href="https://www.oracle.com/webfolder/s/digest/8u31checksum.html" target="_blank">Checksum</a> </div> <br> <b>Looking for JDK 8 on ARM?</b> <br>JDK 8 for ARM downloads have moved to the <a href="/technetwork/java/javase/downloads/jdk8-arm-downloads-2187472.html">JDK 8 for ARM download page.</a></div>';



var downloads = new Array();
downloads['jdk-8u31-oth-JPR'] = new Array();
downloads['jdk-8u31-oth-JPR']['title'] = "Java SE Development Kit 8u31";
downloads['jdk-8u31-oth-JPR']['lictitle'] = "Oracle Binary Code License Agreement for Java SE";
downloads['jdk-8u31-oth-JPR']['licpath'] = "/technetwork/java/javase/terms/license";
downloads['jdk-8u31-oth-JPR']['files'] = new Array();

downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-linux-i586.rpm'] = { "title":"Linux x86", "size":"135.24 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-linux-i586.rpm"};
downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-linux-i586.tar.gz'] = { "title":"Linux x86", "size":"154.91 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-linux-i586.tar.gz"};
downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-linux-x64.rpm'] = { "title":"Linux x64", "size":"135.62 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-linux-x64.rpm"};
downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-linux-x64.tar.gz'] = { "title":"Linux x64", "size":"153.45 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-linux-x64.tar.gz"};
downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-macosx-x64.dmg'] = { "title":"Mac OS X x64", "size":"209.17 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-macosx-x64.dmg"};
downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-solaris-sparcv9.tar.Z'] = { "title":"Solaris SPARC 64-bit (SVR4 package)", "size":"136.91 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-solaris-sparcv9.tar.Z"};
downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-solaris-sparcv9.tar.gz'] = { "title":"Solaris SPARC 64-bit", "size":"97.11 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-solaris-sparcv9.tar.gz"};
downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-solaris-x64.tar.Z'] = { "title":"Solaris x64 (SVR4 package)", "size":"137.51 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-solaris-x64.tar.Z"};
downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-solaris-x64.tar.gz'] = { "title":"Solaris x64", "size":"94.82 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-solaris-x64.tar.gz"};
downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-windows-i586.exe'] = { "title":"Windows x86", "size":"157.96 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-windows-i586.exe"};
downloads['jdk-8u31-oth-JPR']['files']['jdk-8u31-windows-x64.exe'] = { "title":"Windows x64", "size":"170.36 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13/jdk-8u31-windows-x64.exe"};



downloads['jdk-8u31-demos-oth-JPR'] = new Array();
downloads['jdk-8u31-demos-oth-JPR']['title'] = "Java SE Development Kit 8u31 Demos and Samples Downloads";
downloads['jdk-8u31-demos-oth-JPR']['lictitle'] = "Oracle BSD License.";
downloads['jdk-8u31-demos-oth-JPR']['licpath'] = "/technetwork/java/javase/terms/license/oraclebsd-1603217.txt";
//downloads['jdk-8u31-demos-oth-JPR']['licNoAccept'] = true;
downloads['jdk-8u31-demos-oth-JPR']['files'] = new Array();


downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-linux-i586-demos.rpm'] = { "title":"Linux x86", "size":"58.65 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-linux-i586-demos.rpm"};
downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-linux-i586-demos.tar.gz'] = { "title":"Linux x86", "size":"58.5 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-linux-i586-demos.tar.gz"};
downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-linux-x64-demos.rpm'] = { "title":"Linux x64", "size":"58.71 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-linux-x64-demos.rpm"};
downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-linux-x64-demos.tar.gz'] = { "title":"Linux x64", "size":"58.56 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-linux-x64-demos.tar.gz"};
downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-macosx-x86_64-demos.zip'] = { "title":"Mac OS X", "size":"59.22 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-macosx-x86_64-demos.zip"};
downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-solaris-sparcv9-demos.tar.Z'] = { "title":"Solaris SPARC 64-bit", "size":"13.51 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-solaris-sparcv9-demos.tar.Z"};
downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-solaris-sparcv9-demos.tar.gz'] = { "title":"Solaris SPARC 64-bit", "size":"9.27 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-solaris-sparcv9-demos.tar.gz"};
downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-solaris-x64-demos.tar.Z'] = { "title":"Solaris x64", "size":"13.52 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-solaris-x64-demos.tar.Z"};
downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-solaris-x64-demos.tar.gz'] = { "title":"Solaris x64", "size":"9.25 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-solaris-x64-demos.tar.gz"};
downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-windows-i586-demos.zip'] = { "title":"Windows x86", "size":"60.33 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-windows-i586-demos.zip"};
downloads['jdk-8u31-demos-oth-JPR']['files']['jdk-8u31-windows-x64-demos.zip'] = { "title":"Windows x64", "size":"60.43 MB","filepath":"http://download.oracle.com/otn-pub/java/jdk/8u31-b13-demos/jdk-8u31-windows-x64-demos.zip"};


function disableAnchor(obj, disable){
  if(disable){
    var href = obj.getAttribute("href");
    if(href && href != "" && href != null){
       obj.setAttribute('href_bak', href);
    }
    // obj.setAttribute('href', 'http://www.oracle.com/technetwork/licenses/sorry-150381.html');
    obj.removeAttribute('href');
    obj.setAttribute('class', 'boldbodylink');
  } else {
    obj.setAttribute('href', obj.getAttribute('href_bak'));
    obj.setAttribute('class', 'boldbodylink');
  }
}

function disableAnchorByName(anchorname, disable){
//  var use_gebi=false;
    var o=null;
    // if (document.getElementById) { use_gebi=true; }
    // Logic to find position
    // if (use_gebi) {
    //  o=document.getElementById(anchorname);
    // } else {
    for (var i=0; i<document.anchors.length; i++) {
        if (document.anchors[i].name==anchorname) { o=document.anchors[i]; break; }
    }
    disableAnchor(o, disable);
}

function disableAnchorByName(doc, anchorname, disable, enabledHref, onclickFtn){
    var use_gebi=false;
    var o=null;
    for (var i=0; i<doc.anchors.length; i++) {
        if (doc.anchors[i].name==anchorname) { o=doc.anchors[i]; break; }
    }
    disableAnchor(o, disable, enabledHref, onclickFtn);
}

function disableAnchor( obj, disable, enabledHref, onclickFtn ){
  if(disable){
    obj.onclick = onclickFtn;
    // obj.setAttribute('onclick', disabledHref );
    // obj.removeAttribute('href');
    // obj.setAttribute('href', onclickFtn );
    obj.setAttribute('class', 'boldbodylink');
  } else {
    obj.setAttribute('href', enabledHref );
    obj.onclick = null;
    obj.setAttribute('class', 'boldbodylink');
  }
}

function disableDownloadAnchors(doc, disabled, part){

    var agreementPrompt = new Function( "alert('Sorry, you must accept the License Agreement before downloading.');" );

        if (downloads[part]['title']) {     
            for(var b in downloads[part]['files']) {
                if (downloads[part]['files'][b]['title']) {
                    disableAnchorByName(doc, part + 'XXX' + b, disabled, downloads[part]['files'][b]['filepath'], agreementPrompt); 
                }
            }
        }
}

function youMustAgreePrompt(){
    alert('Sorry, you must accept the License Agreement before downloading.');
}

function acceptAgreement(windowRef, part){
    var doc = windowRef.document;
    disableDownloadAnchors(doc, false, part);
    hideAgreementDiv(doc, part);
    writeSessionCookie( 'oraclelicense', 'accept-securebackup-cookie' );
}

function declineAgreement(windowRef, part){
    var doc = windowRef.document;
    disableDownloadAnchors(doc, true, part);
    writeSessionCookie( 'oraclelicense', 'decline' );
    // forward();
}

function showAgreement(part){
    window.open(downloads[part]['licpath'],'LicenseAgreement','status=1,scrollbars=1,width=500,height=400,top=150,left=400');
}

function showAgreement2(part){
    window.open(downloads[part]['licpath2'],'LicenseAgreement','status=1,scrollbars=1,width=500,height=400,top=150,left=400');
}

function forward(){
    location.href="http://www.oracle.com/technetwork/licenses/sorry-150381.html";
}

function hideAgreementDiv(doc, part) {
    if (doc.getElementById) { // DOM3 = IE5, NS6
        doc.getElementById('agreementDiv' + part).style.visibility = 'hidden';
        doc.getElementById('thankYouDiv' + part).style.visibility = 'visible';
    } else {
        if (doc.layers) { // Netscape 4  BROKEN?
            doc.getElementById('agreementDiv' + part).visibility = 'hidden';
            doc.getElementById('thankYouDiv' + part).visibility = 'visible';
        } else { // IE 4  BROKEN?
            doc.all.getElementById('agreementDiv' + part).style.visibility = 'hidden';
            doc.all.getElementById('thankYouDiv' + part).style.visibility = 'visible';
        }
    }
}

function resetAgreementForm(){
    //alert('here 1');
    var cookie = getCookieValue('oraclelicense');
    var myRadios = document.forms['agreementForm']['agreement'];

    if(cookie == null){
        document.forms['agreementForm'].reset();
    } else if(cookie == 'accept-securebackup-cookie') {
        myRadios[0].checked = 'true';
        acceptAgreement(part);
    } else if(cookie == 'decline'){
        myRadios[1].checked = 'true';
    }
}



document.write('<a name="top" id="top"></a><h1>' + page_title + '</h1><br />'); 
document.write(page_blurb + '<br/>'); 


// Add this section in if there are multiple products and you want an anchored table of contents at the top
// document.write('<UL>'); 
// for(var d in downloads) {
//  if (downloads[d]['files']) {
//      document.write('<li><a href="#' + d + '">' + downloads[d]['title'] + '</a></li>');
//  }
// }
// document.write('</ul>'); 

for(var d in downloads) {
    if (downloads[d]['files']) {
        document.write('<br /><table width="100%" border="0" style="border-collapse: collapse; border: 1px solid rgb(204, 204, 204); margin: 1px;"><tbody>');
        if (downloads[d]['title']) document.write('<tr bgcolor="#c0c0c0"><td colspan="3" cellspacing="0" cellpadding="1"><a id="' + d + '" name="' + d + '"></a><h3>&nbsp;' + downloads[d]['title'] + '</h3></td></tr>');

        if (downloads[d]['lictitle'])
          if (downloads[d]['licNoAccept']) {
            document.write('<tr bgcolor="#d0d0d0"><th colspan="3" cellspacing="0" cellpadding="1"><div class="lic_div">');
            document.write('<BR><p>' + downloads[d]['title'] + ' are released under the <a href="' +  downloads[d]['licpath'] + '">' +  downloads[d]['lictitle'] + '</a></p>');
            document.write('</div></th></tr>');               
          } else {
            document.write('<tr bgcolor="#d0d0d0"><th colspan="3" cellspacing="0" cellpadding="1"><div class="lic_div">');
            document.write('<p>You must accept the <a href="javascript:showAgreement(\'' + d + '\');">' +  downloads[d]['lictitle'] + '</a>');
            if (downloads[d]['lictitle2']) document.write(' and <a href="javascript:showAgreement2(\'' + d + '\');">' +  downloads[d]['lictitle2'] + '</a>');       
            document.write(' to download this software.</p>');
            document.write('<div align="left" id="agreementDiv' + d + '"><form name="agreementForm' + d + '" method="post" action="radio" class="lic_form"><input type="radio" value="on" name="agreement' + d + '" onClick="acceptAgreement(window.self, \'' + d + '\');" /> &nbsp;Accept License Agreement&nbsp;&nbsp;&nbsp; <input type="radio" value="on" name="agreement' + d + '" onClick="declineAgreement(window.self, \'' + d + '\');" checked="checked" /> &nbsp; Decline License Agreement</form></div>');
            document.write('<div style="visibility: hidden;" id="thankYouDiv' + d + '" class="com_msg">Thank you for accepting the ' + downloads[d]['lictitle'] + '; you may now download this software.<br/></div>');
            document.write('<br />&nbsp;</div></th></tr>');     
      }

        document.write('<tr bgcolor="#e0e0e0"><th cellspacing="0" cellpadding="1"><h4>&nbsp;Product / File Description</h4></th><th><h4>File Size</h4></th><th><h4>Download</h4></th></tr>');

        for(var e in downloads[d]['files']) {
            if (downloads[d]['files'][e]['title']) {
                if (downloads[d]['lictitle'] && !(downloads[d]['licNoAccept'])) 
                    document.write('<tr valign="top" style="border-bottom:1px solid #CCC; margin-bottom:1px;"><td>&nbsp;' + downloads[d]['files'][e]['title'] + '</td><td align="right">' + downloads[d]['files'][e]['size'] + '&nbsp;&nbsp;</td><td align="left"><a name="' + d + 'XXX' + e + '" href="javascript: void(0)" onclick="youMustAgreePrompt();" id="' + d + 'XXX' + e + '"> <img src="/ocom/groups/public/@otn/documents/digitalasset/115899.gif"> ' + e + '</a></td></tr>');
                else
                    document.write('<tr valign="top" style="border-bottom:1px solid #CCC; margin-bottom:1px;"><td>&nbsp;' + downloads[d]['files'][e]['title'] + '</td><td align="right">' + downloads[d]['files'][e]['size'] + '&nbsp;&nbsp;</td><td align="left"><a name="' + d + 'XXX' + e + '" href="' + downloads[d]['files'][e]['filepath'] + '" id="' + d + 'XXX' + e + '"> <img src="/ocom/groups/public/@otn/documents/digitalasset/115899.gif"> <strong>' + e + '</strong></a></td></tr>');

            }
        }
        // document.write('<tr><td colspan="3" cellspacing="0" cellpadding="1" align="center"><em><a href="#top">Back to top</a></em></td></tr>');
        document.write('</tbody></table>');
    }
}

然后看起来他们有cookie来确定您是否已经同意这些条款,因此您可以下载所有文件链接。

这似乎是下载Cookie代码:

function writeSessionCookie (cookieName, cookieValue) {
    if (testSessionCookie()) {
        var d = new Date();
        d.setTime(d.getTime() + (30*60*1000));
        document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; domain=.oracle.com; path=/; expires=" + d.toGMTString();
        return true;
    }
    else return false;
}

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

function testSessionCookie () {
  document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true
  else
    return false;
}

function testPersistentCookie () {
  writePersistentCookie ("testPersistentCookie", "Enabled", "minutes", 1);
  if (getCookieValue ("testPersistentCookie")=="Enabled")
    return true
  else
    return false;
}

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;

  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years":
      expireDate.setYear(expireDate.getFullYear()+offset);
      break;
    case "months":
      expireDate.setMonth(expireDate.getMonth()+offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate()+offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours()+offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes()+offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  }

  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}

function deleteCookie (cookieName) {
  if (getCookieValue (cookieName)) writePersistentCookie (cookieName,"Pending delete","years", -1);
    return true;
}

我尝试在jsfiddle中使用javascript代码,但它似乎不起作用,所以我认为我错过了一些东西。

关于如何实现这种效果的任何想法?

3 个答案:

答案 0 :(得分:0)

你应该在特定的过程中工作

HTML

<input type="radio" id="radio" value=true>
<button id="startDownload">Download</button>

//设置和获取Cookie的功能

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

//用户点击下载按钮时执行的功能

$("#startDownload").click(function(){
// Condition to check radio button and cookie parameter

    if($("#radio").val() && getCookie("check_radio"))
    {
    // Proceed to download
    }
    else if($("#radio").val())
    {
    setCookie("check_radio", true, 365); // Set Cookie
    // Proceed to download
    }
    else
    {
    alert("Please confirm terms and condition");
    }
});

答案 1 :(得分:0)

使用jQuery Cookie插件:

if($.cookie("accepted")){
    $("#terms").hide();
}

$('#accept').click(function() {
    $.cookie("accepted", true, { expires: 9999 });
    $(this).parent().fadeOut();
});

JSFiddle:http://jsfiddle.net/Tymek/jv6L8ncL/(参见外部资源)

答案 2 :(得分:0)

第一步是学习JavaScript。您不太可能通过复制和粘贴来实现功能。

为此,您需要知道如何检查/设置cookie并进行一些DOM操作。

你的逻辑是

  1. 检查是否设置了接受cookie。
  2. 如果已设置,请将所有文本替换为实际链接。完成。
  3. 如果未设置,则显示文本而不是链接。
  4. 点击接受后,设置cookie并执行步骤2.完成。