简体   繁体   中英

jQuery: set value for element from JSON-object

This may be hard to explain, but I have array object like this:

myobject = {
  "class1"     : "value1",
  "class2"     : "value2",
  "class3"     : "value3",
  ...
}

and I have script

$.each(myobject,function(i,val){
try{
    var it=0;
    $("." + i).each(function(it){
        switch($("." + i)[it].nodeName){
            case "SPAN":case "A":case "DIV":
                $("." + i).html(val);
            break;
            case "INPUT":
                switch($("." + i).attr("type")){
                    case "submit":
                        $("." + i).attr("value",val);
                    break;
                    case "text":case "password":case "email":
                        $("." + i).attr("placeholder",val);
                    break;
                }
            break;
            case "IMG":
                $("." + i).attr("alt",val);
                $("." + i).attr("title",val);
            break;
        }
    });
}catch(err){
    // Nothing
}
});

Effect of code for span , a , div should be this:

Was:  <span class="class1"></span>
Is:   <span class="class1">value1</span>

and for input where type=submit , it should be this:

Was:  <input type="submit" class="class2" />
Is:   <input type="submit" class="class2" value="value2" />

Code effects for span , a , div and input[type=submit] , but this won't set placeholder s. Why?

What you're trying is an overly complicated way to do what you want. Just use the power of the jQuery selector to your advantage to filter by tag type:

$.each(myobject, function(k, v){
    $('span.' + k + ', ' +
      'a.' + k + ', ' +
      'div.' + k).html(v);

    $('input.' + k + '[type="submit"]').val(v);

    $('input.' + k + '[type="text"], ' +
      'input.' + k + '[type="password"], ' +
      'input.' + k + '[type="email"]').attr('placeholder', v);

    $('img.' + k).attr('title', v)
                 .attr('alt', v);
});

EDIT:

See demo

(perhaps you can figure out from looking between the demo and your code what's different and why it's not working)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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