将事件绑定到动态创建的元素

时间:2015-07-02 19:19:13

标签: javascript jquery events

我正在动态创建元素,但是我遇到了将事件附加到这些元素的问题。

以下是代码:

replace()

(我不确定是否有更好的方法来填充选项)

这是我遇到问题的功能:

onHiddenChanged()

根据jquery文档说明将动态元素绑定和事件的正确方法,但它不起作用

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您应该将change事件绑定到<select>元素。由于<select>不是动态创建的,只有<option>,因此您不需要使用委派。然后,您需要测试用户选择的值。所以它应该是:

$("#language").change(function() {
    switch($(this).val()) {
    case "englishEnglish":
        $desiredLanguageEmail = $labelEmailUK;
        $desiredLanguageFirstName = $labelFirstNameUK;
        $desiredLanguageLastName = $labelLastNameUK;
        $desiredLanguageCompany = $labelCompanyUK;
        $desiredLanguageIndustry = $labelIndustryUK;
        $desiredLanguagePhone = $labelPhoneUK;
        $desiredLanguageCountry = $labelCountryUK;
        console.log($desiredLanguageEmail);
        break;
    case "americanEnglish":
        $desiredLanguageEmail = $labelEmailUS;
        $desiredLanguageFirstName = $labelFirstNameUS;
        $desiredLanguageLastName = $labelLastNameUS;
        $desiredLanguageCompany = $labelCompanyUS;
        $desiredLanguageIndustry = $labelIndustryUS;
        $desiredLanguagePhone = $labelPhoneUS;
        $desiredLanguageCountry = $labelCountryUS;
        console.log($desiredLanguageEmail);
        break;
    ...
}

仅供参考,没有必要在$("#language").html("")之前使用$("#language").html(somethingElse),因为第二个声明取代之前的任何内容。

此外,不是使用7个不同的变量,而是使用巨大的switch语句来为每种语言设置不同的语句,最好创建一个收集它们的对象,键入语言:

var langLabels = {
    "englishEnglish": {
        email: "Email",
        firstName: "First Name",
        lastName: "Surname",
        company: "Company",
        industry: "Industry",
        phone: "Phone #",
        country: "Country"
    },
    "frenchfrench": {
        email: "Email",
        firstName: "Prénom",
        lastName: "Nom de Famille",
        company: "Compagnie",
        industry: "Industrie",
        phone: "Téléphone",
        country: "Pays"
    },
    ...
}

然后你的.change处理程序可以执行:

var $desiredLanguage = $langLabels[$(this).val()];
$desiredLanguageEmail = $desiredLanguage.email;
$desiredLanguageFirstName = $desiredLanguage.firstName;
...

答案 1 :(得分:0)

您需要将change事件绑定到select而不是其中一个选项:

$('body').on('change', '#yourLanguageSelectId', function () {
    $desiredLanguageEmail = $labelEmailUK;
    $desiredLanguageFirstName = $labelFirstNameUK;
    $desiredLanguageLastName = $labelLastNameUK;
    $desiredLanguageCompany = $labelCompanyUK;
    $desiredLanguageIndustry = $labelIndustryUK;
    $desiredLanguagePhone = $labelPhoneUK;
    $desiredLanguageCountry = $labelCountryUK;
    console.log($desiredLanguageEmail);
});

答案 2 :(得分:0)

试试这个(假设#country是你选择元素的id):

$(document).on('change', '#country', function() {
    // do whatever you wanted to do here
});