简体   繁体   English

JavaScript:用 jQuery 获取一个值并替换它

[英]JavaScript: get a value with jQuery and replace it

I have a gender selector, and a script that gets the value of the selected gender and pastes it on a label, but it's pasting the value: "M" or "F".我有一个性别选择器和一个脚本,它获取所选性别的值并将其粘贴到标签上,但它正在粘贴值:“M”或“F”。

<div name="userLabelDiv" id="genderUserLabelDiv">
    <label class="required">Sexo</label>    
    <label id="genderLabel">F</label> 
</div>

Now when I'm trying to get this letter and replace for the actual gender, I'm missing on the JS script.现在,当我尝试获取这封信并替换实际性别时,我在 JS 脚本中丢失了。 Could you help me?你可以帮帮我吗?

$("#genderLabel").html(
    if ($(this).value == 'F') {
        this.value = 'Female';
    }
    if ($(this).value == 'M') {
        this.value = 'Male';
    }
);

I know the script is probably wrong, could someone correct it, please?我知道脚本可能是错误的,有人可以更正吗? Thank you!谢谢!

var gender = $('#genderLabel');
if (gender.text() == 'F') { gender.text('Female'); }
else { gender.text('Male'); }

replace every value with text()text()替换每个value

if($(this).text()=='F'){
   $(this).text('Female');
}
if($(this).text()=='M'){
    $(this).text('Male');
}

Among a few other things除了其他一些事情

In jQuery 1.4+ you can pass a function to .text() like this:在 jQuery 1.4+ 中,您可以像这样将函数传递给.text()

$("#genderLabel").text(function(i, t) {
   return t == 'F' ? 'Female' : t == 'M' ? 'Male' : t;
});

This converts F to Female , M to Male and leaves anything else alone, in case new genders come up :)这会将F转换为Female ,将M转换为Male并留下任何其他内容,以防出现新的性别:)

To use .html() that way, you need to pass a function as the argument that returns the value you want.要以这种方式使用.html() ,您需要传递一个function作为返回所需值的参数。

Try it out: http://jsfiddle.net/FDZBJ/试试看: http : //jsfiddle.net/FDZBJ/

$("#genderLabel").html(function(i,html) {
                           html = $.trim(html);
                           if(html == 'F') return 'Female';
                           if(html == 'M') return 'Male';
                           return html;
                       });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM