开发者

jQuery prepend to all hyperlink elements that link to PDF files

开发者 https://www.devze.com 2022-12-19 05:06 出处:网络
I would like to prepend \"Download a PDF of \" to any hyperlinks, linking to PDF files. Currently I\'m able to prepend that exact text, but it prepends it to the hyperlink text. I would like it to res

I would like to prepend "Download a PDF of " to any hyperlinks, linking to PDF files. Currently I'm able to prepend that exact text, but it prepends it to the hyperlink text. I would like it to reside outside of the hyperlink element, like so: Download开发者_Go百科 a PDF of [hyperlink with text]

This is the code I'm using now:

jQuery('a[href$=.pdf]').prepend('Download a PDF of ');


Have you tried before?

jQuery('a[href$=.pdf]').before('Download a PDF of ');


The other selectors that have been provided in answers are wrong, as of today anyway. jQuery will complain:

Uncaught Error: Syntax error, unrecognized expression: a[href$=.pdf]

The right way to select the anchor is:

jQuery('a[href$=".pdf"]');

Note the quotes around .pdf


You could wrap it up in an inline element (e.g. <span>) and insert it before the desired elements. Here's an SSCCE, just copy'n'paste'n'run it:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2172666</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                $('<span>Download a PDF of </span>').insertBefore('a[href$=.pdf]');
            });
        </script>
    </head>
    <body>
        <p><a href="foo.pdf">foo.pdf</a></p>
        <p><a href="foo.exe">foo.exe</a></p>
        <p><a href="bar.pdf">bar.pdf</a></p>
    </body>
</html>

Edit: ah, as answered before, the jQuery.before() works exactly the way you want, so I would go for it instead.


Here's an example that will do what you're looking for:

<a href="foo.pdf">Foo</a>
<a href="bar.pdf">Bar</a>
<span id='foo'>Download a pdf of </span>
<script type='text/javascript'>
$('#foo').insertBefore('a[href$=.pdf]');
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消