使用jQuery获取链接并生成带该链接的新按钮(无源码权限)
Got it, here's a clean jQuery solution that does exactly what you need—no need to touch the existing page source at all:
// Wait for the DOM to fully load before running our code $(document).ready(function() { // Step 1: Fetch the target URL from the existing link const targetLink = $('.product-buttons .button-info').attr('href'); // Only proceed if we successfully found the URL (avoids errors if elements are missing) if (targetLink) { // Step 2: Build a new button element (using <a> since we need an href attribute) const newProductButton = $('<a>', { 'class': 'button-custom', // Add a class for styling (match your site's button classes if needed) 'href': targetLink, // Assign the copied URL to the button's href 'text': 'View Product' // Customize this to your preferred button text }); // Step 3: Insert the button into the page (example: right after the price section) $('.product-price').after(newProductButton); } });
Breakdown of how this works:
- DOM Ready Check:
$(document).ready()ensures we don't try to interact with elements before they're loaded on the page, preventing errors. - Grab the Target URL: The selector
$('.product-buttons .button-info')targets the exact link you want to copy, and.attr('href')pulls its URL value. - Error Safety: The
if (targetLink)check stops the code from running if the target link can't be found, so you won't get console errors if the page structure changes unexpectedly. - Build the Button: jQuery's
$('<a>')syntax lets us create the button and set all its attributes (class, href, text) in one clean step. - Place the Button:
.after(newProductButton)inserts the button right after the price section—you can tweak this to use.appendTo('.product-buttons')(add inside the existing buttons div) or.insertBefore('.product-price')(place before the price) depending on your layout needs.
Quick Customization Tips:
- Change the
textvalue to whatever fits your use case (e.g., "Shop Now", "Learn More"). - Swap the
classvalue to match your site's existing button styles, or add inline styles with.css({'padding': '10px', 'background': '#007bff'})if needed.
内容的提问来源于stack exchange,提问作者felsjo
相关产品推荐
相关产品推荐

