jQuery Jquery中的函数将表单元素的ID作为参数传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6005570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:12:43  来源:igfitidea点击:

Function in Jquery passing form element's ID as parameter

jqueryfunctionparameters

提问by Raju Rimal

I'm trying to make a function in Jquery that will take the ID of form SELECT element's ID where a dynamically created option should be displayed. But, i have to repeat this work for other form instances as well. i have created the following code, but it did not work.

我正在尝试在 Jquery 中创建一个函数,该函数将采用表单 SELECT 元素 ID 的 ID,其中应显示动态创建的选项。但是,我也必须为其他表单实例重复这项工作。我创建了以下代码,但它不起作用。

JQuery Script

jQuery 脚本

function getOffice(ID){
    $.post('dynamicOffice.php',{operator:$(this).val()},function(output){
    $('ID').html(output);
    });
        $('ID').removeAttr('disabled');
}

Main HTML File

主 HTML 文件

<select id="senderOperator" name="senderOperator" tabindex="1" onchange=getOffice(sender)>
    <option value=""><--SELECT an Operator --></option>                 
        <?php getOption($operator,Operator) ?>
</select>

<select id="sender" name="sender" tabindex="1" disabled="disabled">
    <option value=""><--SELECT the Operator First --></option>
</select>

dynamicOffice.php

动态Office.php

<?php
include('generateOption.php');
    $country=$_POST['operator'];
    $officeSql="SELECT * FROM myoffice WHERE Operator='$country'";
    getOption($officeSql,Name);
?>

generateFormElement.php

生成表单元素.php

<?php
include("include/dbConnect.php");       

function getOption($rsSql,$colName){

    $sResult=mysql_query($rsSql) or die("Could Not Fetch Records");

    while ($s_Office = mysql_fetch_array($sResult))
    {
        echo("<option value='".$s_Office["$colName"]."'>".$s_Office["$colName"]."</option>");
    }
}
?>

回答by user113716

Remove the quotes from around the parameter, and concatenate a #to the beginning of it.

删除参数周围的引号,并将 a 连接#到它的开头。

$('#' + ID).html(output);

$('#' + ID).removeAttr('disabled');

Also, thiswill likely reference the windowinstead of whatever element you expect, so the following won't work:

此外,this可能会引用window而不是您期望的任何元素,因此以下内容不起作用:

{operator:$(this).val()}

If it should reference the selectelement, then add thisas a second argument:

如果它应该引用该select元素,则添加this作为第二个参数:

onchange=getOffice(sender,this)

...and reference it with a parameter:

...并使用参数引用它:

function getOffice(ID, el){
    $.post('dynamicOffice.php',{operator:$(el).val()},function(output){
        $('#' + ID).html(output);
    });
    $('#' + ID).removeAttr('disabled');
}