jQuery :file 選擇器



jQuery 中的:file 選擇器用於選擇所有型別為 file 的 <input> 元素。

<input type ="file"> 元素用於 HTML 表單中建立一個控制元件(通常是一個標記為“選擇檔案”的按鈕),允許使用者從其裝置選擇並上傳檔案到 Web 伺服器。

語法

以下是 jQuery 中 :file 選擇器的語法:

$(":file")

引數

以下是此方法的引數:

  • ":file" − 此選擇器選擇所有型別為 file 的 <input> 元素。

示例 1

在以下示例中,我們使用 :file 選擇器為所有檔案輸入元素應用藍色邊框:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("input:file").css("border", "2px solid blue");
        });
    </script>
</head>
<body>
    <form>
        <label for="file1">Choose file:</label>
        <input type="file" id="file1" name="file1"><br><br>
        <label for="file2">Choose another file:</label>
        <input type="file" id="file2" name="file2"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

執行上述程式後,型別為“file”的 <input> 元素將被選中,並在其周圍突出顯示藍色邊框。

示例 2

此示例使用 :file 選擇器設定一個事件處理程式,當用戶選擇檔案時,該處理程式會提示所選檔案的路徑:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("input:file").on("change", function() {
                alert("File selected: " + $(this).val());
            });
        });
    </script>
</head>
<body>
    <form>
        <label for="file3">Select a file:</label>
        <input type="file" id="file3" name="file3"><br><br>
        <label for="file4">Select another file:</label>
        <input type="file" id="file4" name="file4"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

執行後,單擊“選擇檔案”按鈕並上傳任何檔案。然後將彈出一個警報,顯示上傳檔案的路徑。

jquery_ref_selectors.htm
廣告