Javascript:根据选择值更改文本

时间:2014-11-20 22:45:55

标签: javascript jquery html

我已经为每个javascript添加了一个带有文本的元素。使用此代码:

$(document).ready(function () {
   if ($('welcome_page').length) {
   $('#my_element').after('<tr><td><td><td id="welcome_message">Welcome to my page</td></td></td</tr>');
   }
});

我需要能够更改文字&gt;欢迎使用我的页面&lt;取决于页面中设置的语言:

<select id="languages" onchange="submit();">
<option value="1" selected="">English</option>
<option value="2">Spanish</option>
<option value="3">French</option>
</select>

我已经尝试了这个但是没有做到这一点:

function langChoice(sel){
    var langChange = document.getElementById('languages');
    var langOption = document.getElementById('welcome_message');
        if ( sel.options[sel.selectedIndex].value == "1" ) {
        langOption.innerHTML = "Enter price per month";
        }
        else if ( sel.options[sel.selectedIndex].value == "2" ) {
        langOption.innerHTML = "Enter price per week";
        }
        else if ( sel.options[sel.selectedIndex].value == "3" ) {
        langOption.innerHTML = "Enter price per day";
        }
        else if ( sel.options[sel.selectedIndex].value == "4" ) {
        langOption.innerHTML = "Enter for sale hour";
        }

}

4 个答案:

答案 0 :(得分:0)

也许..

$(document).ready(function () {
   if ($('welcome_page').length) {
   $('#my_element').after('<tr><td><td><td id="welcome_message">Welcome to my page</td></td></td</tr>');

   langChoice($("#languages"))

   }
});

我认为页面中存在下拉菜单#languages;我没有找不到$(&#34; welcome_page&#34;)..也许$(&#34;#welcome_page&#34;)或者你使用标签??

答案 1 :(得分:0)

好的,然后在submit()函数的第一行内调用函数langChoice(sel)

例如: -

function submit() {
  langChoice($("#languages"));

  .. your logic ..
}

答案 2 :(得分:0)

我猜......

访问此JsFiddle

HTML:

<div id="greet"></div>
<select id="languages">
    <option value="en" >English</option>
    <option value="es" selected>Spanish</option>
    <option value="fr">French</option>
</select>

JS:

var welcome = {
    en:"English",
    es:"Espanol",
    fr:"Francais"
}
$(document).ready(function () {
    $('#greet').html(welcome[$('#languages').val()]);
});

$('#languages').change(function () {
    $('#greet').html(welcome[$('#languages').val()]);
});

答案 3 :(得分:0)

如果我理解正确:

<div id="welcome_page">
    <select id="languages" onchange="submit();">
        <option value="1" selected="">English</option>
        <option value="2">Spanish</option>
        <option value="3">French</option>
    </select>
    <div id="my_element"></div>
</div>

$(document).ready(function () {

    if ($('#welcome_page').length) {
       $('#my_element').after('<tr><td><td><td id="welcome_message">Welcome to my page</td></td></td</tr>');
    }

$("#languages").on("change",function(){
    var Val = $(this).val();

    if(Val==1){
        $("#welcome_message").html("English");
    }
    else if(Val==2){
        $("#welcome_message").html("Spanish");
    }
    else if(Val==3){
        $("#welcome_message").html("French");
    }

});


});

小提琴:http://jsfiddle.net/tufce1yo/