簡體   English   中英

使用jQuery獲取多個元內容值?

[英]Get multiple meta content values using jQuery?

使用jQuery獲取多個元標記值的最有效方法是什么? 我在要通過jQuery讀取的meta標簽中存儲了一些值,然后傳遞給ajax調用或基於UI進行更改。 我正在處理的代碼庫目前有這個...

params: {
    ad_hash:                $('meta[property=ad_hash]').attr('content'),
    ad_id:                  $('meta[property=ad_id]').attr('content'),
    ad_advertiser_id:       $('meta[property=ad_advertiser_id]').attr('content'),
    ad_subcategory_id:      $('meta[property=ad_subcategory_id]').attr('content'),
    ad_est_firstoccur:      $('meta[property=ad_est_firstoccur]').attr('content'),
    ad_est_lastoccur:       $('meta[property=ad_est_lastoccur]').attr('content'),
    ad_firstoccur:          $('meta[property=ad_firstoccur]').attr('content'),
    ad_lastoccur:           $('meta[property=ad_lastoccur]').attr('content'),
    ad_time:                $('meta[property=ad_time]').attr('content'),
    ad_timestamp:           $('meta[property=ad_timestamp]').attr('content'),
    ad_rating:              $('meta[property=ad_rating]').attr('content'),
    hostname:               $('meta[property=hostname]').attr('content'),
    user_clientip:          $('meta[property=user_clientip]').attr('content'),
    user_searchterm:        $('meta[property=user_searchterm]').attr('content'),
    user_voted:             $('meta[property=user_voted]').attr('content'),
    trans_recentlyaired:    $('meta[property=trans_recentlyaired]').attr('content'),
    trans_lastaired:        $('meta[property=trans_lastaired]').attr('content'),
    trans_on:               $('meta[property=trans_on]').attr('content'),
    trans_during:           $('meta[property=trans_during]').attr('content'),
    trans_tobeaired:        $('meta[property=trans_tobeaired]').attr('content')
},

是否有比捕獲dom多次旅行更有效的方法來獲取多個meta標簽值? 這是我考慮過的一些替代解決方案...

  • 我可以通過添加head來限制范圍:$('meta [property = ad_hash]','head')。attr('content')
  • 我可以將所有值存儲在單個JSON字符串中,但是在從meta標記讀取它時遇到了一些問題。
  • 有沒有一種方法可以使用$('meta')將匹配項存儲到變量中,然后訪問其中的各個標簽?

在大小上使用JSON字符串會更有效,但是本質上您只是在解析XML數據。 您可以遍歷meta標簽,以減少從DOM中選擇的頻率,並使代碼更具動態性:

var params = {};
$('head meta[property][content]').each(function() {
    params[$(this).attr('property')] = $(this).attr('content');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM