Accessing dynamic property names in Jquery/Javascript

前端 未结 3 1718
不知归路
不知归路 2020-12-22 03:23

In a plugin I\'m writing, the dev can specify options, which I\'m storing and referencing like so:

(function( $, window) {
    $.widget(\"mobile.plug\", $.mo         


        
相关标签:
3条回答
  • 2020-12-22 03:31

    What you're looking for is bracketed notation with strings:

    for (var i = 0; i<elems.length; i++){
       var el = elems.eq(i);
       console.log( o[el.jqmData("panel") + "Width"] );
       }
    

    ...assuming that el.jqmData("panel") returns "mid", "menu", etc.

    In JavaScript, you can refer to a property with either dotted notation and a literal (obj.foo), or bracketed notation and a string (obj["foo"]). In the latter case, it doesn't have to be a literal string, it can be the result of an expression.

    0 讨论(0)
  • 2020-12-22 03:34

    You're getting the error because you're trying to use both forms of the object member operator.

    The two forms are...

    • obj.propertyName dot notation

    • obj["propertyName"] bracket notation

    You have .[...] (using both. The dot expects a name to come after it)

    You need [...] (no preceding dot)

    Then also, you want to do string concatenation to add "Width"

    o[el.jqmData("panel") + "Width"]
    
    0 讨论(0)
  • 2020-12-22 03:39

    You should be able to concatenate "Width" to the "panel" result:

    o[el.jqmData("panel") + "Width"]
    

    E.g., if el.jqmData("panel") is "menu" you would get o["menuWidth"].

    0 讨论(0)
提交回复
热议问题