简体   繁体   English

JS将属性添加到字符串

[英]JS add attribute to string

I have a post ajax that return retorno1 and just to get it simple i put their output as string value as ajax posted like the example .. then I need to add more than 1 option that the value is 0 so I need to say if the value is 0 show the selected item "NON" and if the value other so show it and select it. 我有一个返回retorno1的ajax retorno1 ,只是为了简单retorno1 ,我将它们的输出作为字符串值作为ajax发布,例如示例..然后我需要添加多个选项,该选项的值是0,所以我需要说一下如果值为0,则显示所选的项目“ NON”;如果其他值为,则显示并选择它。

I'm using setAttribute("selected", "selected") but I know it's wrong, so what is the correct code to add attribute to this string? 我正在使用setAttribute("selected", "selected")但我知道这是错误的,那么将属性添加到此字符串的正确代码是什么?

var i = 0;
var returno1 = "<option value='21'>Hello</option><option value='22'>Bye</option>";
var pre = retorno1 + '<option value="0">------ N/A ------</option>';
var count = $($.parseHTML(pre)).filter('option').length;
var dep_dr = $("#departamento_drop option:selected").val();

$.each($.parseHTML(pre),function(i,item){
    var val_drop  =($(item).val());
    var text_drop =($(item).html());

    if (val_drop == dep_dr){
        jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
    }else if(dep_dr == "0"){
        jQuery("#departamento_drop").html(pre).setAttribute("selected", "selected");
    }
})

Working fiddle 工作提琴

Try to use attr() or prop() to set or get attribute to elements, check example bellow : 尝试使用attr()prop()来设置或获取元素的属性,请检查以下示例:

jQuery("#departamento_drop").empty();

$.each($.parseHTML(pre),function(i,item){
    var current_itme=$(item);
    var val_drop  =current_itme.val();
    var text_drop =current_itme.html();

    if (val_drop == dep_dr || dep_dr == "0"){
        current_itme=current_itme.attr("selected", "selected");
    }

    jQuery("#departamento_drop").append(current_itme);
})

Hope this helps. 希望这可以帮助。

Why do you need use strings? 为什么需要使用字符串? Use objects insted. 使用插入的对象。

var values = [{val:33, title:'Hi'},{val:34, title:'Bue'},{val:0, title:'-------NA-------'}],
    selected = 34;
values.forEach(function(item){
    $('#dd').append($('<option>', {value:item.val, text:item.title, selected: item.val==selected}));
})

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

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