next.js 将附加有href的标记复制到HTML

camsedfj  于 2023-10-18  发布在  其他
关注(0)|答案(2)|浏览(94)

我正在创建一个网址缩短作为一个个人项目,我试图使一个复制按钮,当点击复制缩短的网址与所附的超链接。
URL缩短是用Formik和Yup处理的,我使用clipboard.js复制链接。这是我第一次使用所有这些API(?).
目前,当单击复制按钮时,它复制缩短的URL,但不复制附加的超链接。因此,当缩短的URL被粘贴到搜索栏时,这是一个死胡同。
我已经搜索了如何做到这一点,但我找不到相关的信息。我将感谢任何帮助如何解决这个问题。
下面是我目前拥有的:

export default function Home() {
    // =========== shortener = shortens the given url ===========
    const shortener = new Shortener({
        target: "https://short.ie/",
        length: 8,
        alphabet: "alphanumeric",
    });

    // =========== formik (= saves the form's data before and after submit) ===========
    const formik = useFormik({
        // what is saved while typing into the input box
        initialValues: {
            link: "",
        },
        validationSchema: Yup.object({
            link: Yup.string()
                .matches(
                    /((https?):\/\/)?(www.)?[a-z0-9]+(\.[a-z]{2,}){1,3}(#?\/?[a-zA-Z0-9#]+)*\/?(\?[a-zA-Z0-9-_]+=[a-zA-Z0-9-%]+&?)?$/,
                    "Please enter a valid url"
                )
                .required("A URL is required"),
        }),
        onSubmit: (values) => {
            setShortURL(shortener.shorten(values.link));
        },
    });

    const clipboard = new ClipboardJS(".copy-btn");

    const [shortURL, setShortURL] = useState("");

    return (
        <div id="container">
            <div className="header-container">
                <h1 id="header">URL Shortie</h1>
            </div>
            <div className="form-container">
                <form onSubmit={formik.handleSubmit}>
                    {/* if the input has been "touched" (i.e. clicked on) and there is an error, display the error, else display 'your long url' */}
                    <label className="label">
                        {formik.touched.link && formik.errors.link
                            ? formik.errors.link
                            : "Your Long URL"}
                    </label>
                    <input
                        className="input"
                        type="url"
                        name="link"
                        value={formik.values.link}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        placeholder="Enter your link here"
                        required
                    />

                    <p className="label">Shortened URL HTML Div</p>
                    <div className="input copy">
                        {/* if shortURL is not empty then render shortend url,
                         else render onsubmit */}
                        {shortURL ? (
                            shortURL && (
                                <a id="result" href={shortURL.original} target="_blank">
                                    {shortURL.target}
                                </a>
                            )
                        ) : (
                            <a id="result" href="">
                                https://short.ie/
                            </a>
                        )}
                    </div>

                    <label htmlFor="" className="label">
                        Shortened URL HTML Input
                    </label>
                    {/* if shortURL is not empty render the target URL, else render base URL */}
                    <input
                        id="shortenedURL"
                        className="input"
                        type="text"
                        value={shortURL ? shortURL.target : "https://short.ie/"}
                        readOnly="readOnly"
                    />

                    <div className="button-container">
                        <input className="submit-btn" type="submit" value="Shorten Url" />

                        <button
                            className="copy-btn"
                            type="button"
                            data-clipboard-action="copy"
                            data-clipboard-target="#result"
                        >
                            <span class="material-symbols-outlined">content_copy</span>
                            Copy
                        </button>
                    </div>
                </form>

                <h1 id="subheader">Previous URLs</h1>
                <div className="previous-urls-container"></div>
            </div>
        </div>
    );
}
hgb9j2n6

hgb9j2n61#

下面的输入框-> Shortened URL HTML输入文本应首先使用缩短的URL进行更新。我没有看到它得到更新与缩短网址。一旦它的更新,然后你可以只读取输入框的值上点击复制按钮。

<button onClick="copyClickHandler" class="copy-btn" type="button" data-clipboard-action="copy" data-        
 clipboard-target="#result"><span class="material-symbols-     
 outlined">content_copy</span>Copy</button>

添加一个点击处理程序,它将从输入框中复制URL。

function copyClickHandler() {
        // Get the input element
        var inputElement = document.getElementById("shortenedURL");
        
        // Select the text in the input element
        inputElement.select();
        
        // Copy the selected text to the clipboard
        document.execCommand("copy");
        
        // Deselect the input element
        inputElement.setSelectionRange(0, 0);
        
        // Optionally, provide user feedback
        alert("Copied to clipboard: " + inputElement.value);   
}
w8f9ii69

w8f9ii692#

你是否需要使用Clipboard.js来复制文本,或者你可以使用简单的JavaScript代码来复制文本?如果没有,您可以使用以下JavaScript代码来完成此任务:

document.getElementById('copybuttonid').addEventListener('click', function() {
    const textToCopy = document.getElementById("linkid").innerText;
    const tempTextarea = document.createElement('textarea');
    tempTextarea.value = textToCopy;
    document.body.appendChild(tempTextarea);
    tempTextarea.select();
    document.execCommand('copy');
    document.body.removeChild(tempTextarea);
    alert(`Copied to Clipboard`);  //alert once copied the link
});

相关问题