6

jQueryを使用して、ファイル拡張子を持つすべてのリンクを.pdf新しいウィンドウで開くにはどうすればよいですか?これを変更する必要があります:

<a href="domain.com/pdf/parkingmap.pdf">parking map</a>

これに:

<a href="domain.com/pdf/parkingmap.pdf" target="_blank">parking map</a>

/pdfそれが助けになるなら、すべてのファイルはフォルダにあります。

4

4 に答える 4

21

これを実現するには、で終わるプロパティaを持つ要素を選択し、それに属性を追加します。これを試して:href.pdftarget="_blank"

$(function() {
    $('a[href$=".pdf"]').prop('target', '_blank');
});
于 2013-01-03T14:06:39.137 に答える
3

1つの方法は、で終わらないpdfリンクを同じページで開くことを想定しています。

$('a').click(
    function(e){
        e.preventDefault();
        if (this.href.split('.').pop() === 'pdf') {
            window.open(this.href);
        }
        else {
            window.location = this.href;
        }
    });
于 2013-01-03T14:08:17.963 に答える
2

jQueryワンライナー:

$('a[href$=".pdf"]').attr('target','_blank');

現在のJavascript:

for (let a of document.querySelectorAll("a")) {
    if (a.href.match("\\.pdf$")) {
        a.target = "_blank";
    }
}

古いブラウザ:

var anchors = document.body.getElementsByTagName('a');
for (var i = 0; i < anchors.length; i++) {
    if(anchors[i].getAttribute('href').match('\\.pdf$') {
        anchors[i].setAttribute('target', '_blank');
    }
}

ここで試してみてください:http://codepen.io/gabssnake/pen/KyJxp

于 2014-11-07T10:42:58.193 に答える
1

<a onclick=ViewPdf(test.pdf) href="">


function ViewPdf(FileName) {
    var url = '../Home/GetPDF?fileName=' + FileName;
    window.open(url, '_blank');

}

次に、以下のようにActionResultを記述します

public ActionResult GetPDF(string fileName)
        {
            try
            {
                byte[] fileData = System.IO.File.ReadAllBytes(Functions.GetConfigValue("CDXFilePath") + fileName);
                string resultFileName = String.Format("{0}.pdf", fileName);
                Response.AppendHeader("Content-Disposition", "inline; filename=" + resultFileName);
                return File(fileData, "application/pdf");
            }
            catch
            {
                return File(Server.MapPath("/Content/") + "FileNotFound.html", "text/html");
            }
        }
于 2019-05-22T14:51:56.517 に答える