简体   繁体   English

通过 Jquery 向 HTML 元素添加属性

[英]Adding Attributes to HTML elements via Jquery

I am using wordpress and there is no way to add custom attribute to HTML element via theme.我正在使用 wordpress 并且无法通过主题将自定义属性添加到 HTML 元素。 I found that it can be done via Jquery, but it doesn't help me.我发现它可以通过 Jquery 完成,但这对我没有帮助。

Attributes that I want to add to HTML element on load (No need to click anything specific):我想在加载时添加到 HTML 元素的属性(无需单击任何特定内容):

data-tf-popup="Vxs1VOeK" 
data-tf-hide-headers="" 
data-tf-transitive-search-params="utm_source, utm_medium,utm_campaign,utm_term,utm_content" 
data-tf-iframe-props="title=Dermatologo konsultacija internetu - iDerma" 
data-tf-medium="snippet" 
data-tf-hidden="utm_source=xxxxx,utm_medium=xxxxx,utm_campaign=xxxxx,utm_term=xxxxx,utm_content=xxxxx" 

Specific button/item to which I want to add it.我要添加它的特定按钮/项目。 Currently it has Ahref, but I will remove the ahref, to keep it empty.目前它有 Ahref,但我将删除 ahref,以保持其为空。

<li id="menu-item-37" class="menu-singup menu-item menu-item-type-custom menu-item-object-custom menu-item-37" data-tf-popup="Vxs1VOeK"><a href="https://form.typeform.com/to/Vxs1VOeK">Pradėti konsultaciją</a></li>

Any help will be appreciated!任何帮助将不胜感激!

You can add the attributes via jQuery's .attr() function .您可以通过 jQuery 的.attr() function添加属性。 The first parameter determines the attribute you're adding while the second parameter is the value of the said attribute.第一个参数确定您要添加的属性,而第二个参数是所述属性的值。

Example:例子:

$(document).ready(() => {
  $('#element_id').attr('data-tf-popup', 'Vxs1VOeK');
  $('#element_id').attr('data-tf-hide-header', '');
  // ...
});

You can make it cleaner by using JSON objects as such:您可以通过使用 JSON 对象使其更清洁:

$(document).ready(() => {
  const attr = {
    'data-tf-popup': 'Vxs1VOeK',
    'data-tf-hide-header': '',
    'data-tf-transitive-search-params': 'utm_source, utm_medium,utm_campaign,utm_term,utm_content',
    // ...
  }
  
  for (let key in attr) {
    $('#element_id').attr(key, attr[key]);
  }
});

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

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