简体   繁体   English

为什么我的语句没有更改并添加锚标记的属性?

[英]Why doesn't my statement change and add attributes for anchor tag?

I'm trying to change the value of anchor tag and also add new attributes but it does not seem to work. 我正在尝试更改锚标记的值,并添加新属性,但它似乎不起作用。

document.getElementsByClassName('button')[0]
  .getElementsByTagName('a')[0]
  .attr({ 
    href: '#', 
    data: 'xyz', 
    name: 'test'
  });

The problem is that you're attempting to use a jQuery method on a native DOM element. 问题是您试图在本机DOM元素上使用jQuery方法。 My guess is that your browser's throwing an error indicating such. 我的猜测是您的浏览器抛出了一个错误提示。

Instead, use jQuery syntax to create an actual jQuery object: 而是使用jQuery语法创建实际的jQuery对象:

$('.button a').attr({ ... });

This has the bonus benefit of being a fraction as long. 这样做的好处是它的分数很长。

In case you actually need to select the first of the elements jQuery grabs with that selector, use first() : 如果您确实需要使用该选择器选择jQuery捕获的第一个元素,请使用first()

$('.button a').first().attr({ ... });

This filters the jQuery object into a new one without converting to a native DOM element. 这会将jQuery对象过滤为一个新对象,而无需转换为本地DOM元素。 It's fragile, however, because it depends on your markup for accurate selection. 但是,它很脆弱,因为它取决于您的标记以进行准确选择。 I'd prefer to add another class to that button or target an ancestor element for specificity: 我宁愿向该按钮添加另一个类,或针对其祖先元素进行定位:

$('.button.my-extra-class a').attr({ ... });

I've put together an example of how you can set attributes. 我整理了一个有关如何设置属性的示例。

 let link = document.getElementsByTagName('a')[0]; link.setAttribute("href", "http://www.google.com"); link.setAttribute("data", "xyz"); link.setAttribute("data-name", "test"); 
 <ul> <li> <a href="#">A link</a> </li> </ul> 

https://codepen.io/anon/pen/vaNZKd https://codepen.io/anon/pen/vaNZKd

Here's some more info on setting attributes: https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute 以下是有关设置属性的更多信息: https : //developer.mozilla.org/zh-CN/docs/Web/API/Element/setAttribute

$("button")
    .first()
    .find("a")
    .first()
    .attr('href', '@')
    .attr('data', 'xyz')
    .attr('name', 'test');

What this means is that you're getting the first <button> , then the first <a> within that button, and then assigning the data. 这意味着您将获得第一个<button> ,然后是该按钮内的第一个<a> ,然后分配数据。

Based on your code, I assume this is what you want. 根据您的代码,我假设这就是您想要的。

You can try querySelectorAll 您可以尝试使用querySelectorAll

  let anchor = document.querySelectorAll('a.button')[0]; anchor.setAttribute("href", "http://www.google.com"); 
  <a href="#" class="button">A link - will be affected</a><br/> <a href="#" class="button">B link - not affected</a><br/> <a href="#">C link - not affected</a><br/> <a href="#">D link - not affected</a><br/> 

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

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