EDIT:

我了解到,使用_blank以外的值在移动浏览器上无法打开新的窗口/选项卡.

For example, if you need to open a new window/tab:

  • This works在所有浏览器上,甚至在移动浏览器上:target="_blank".

  • 在移动浏览器上是This does not work,但在桌面浏览器上是does work:target="new"

--

Although I have this one working, I'm not sure if there's a better way to do it, or if the way I got it is the right/only way.

Basically what I'm doing is replacing all the target="_new" or target="_blank" attribute values to target="nw", this way only one new window is open and in it all other new windows will open in order to not overwhelm the user with multiple windows.

我还添加了一个"Opens in a new window"title=""属性.

So the solution I created is this one:

$("a[target='_blank'], a[target='_new']").attr('target','nw').attr('title','Opens in a new window');

注意这两种方法.

Is this the correct way to add two attributes to an element?

我试了.attr('target','nw','title','Opens in a new window')次,但不起作用.

我问这个问题的原因是因为DYR(不要重复你自己)原则,所以如果我能改进我的代码,很好,如果不能,那就是它.

谢谢

推荐答案

应该有效:

.attr({
    target:"nw", 
    title:"Opens in a new window",
    "data-value":"internal link" // attributes which contain dash(-) should be covered in quotes.
});

Note:

" When setting multiple attributes, the quotes around attribute names are optional.

100: When setting the 'class' attribute, you must always use quotes!

根据jQuery文档(2016年9月)中的.attr:

试图更改通过文档创建的输入或按钮元素的type属性.createElement()将在Internet Explorer 8或更早版本上引发异常.

Edit:
For future reference... To get a single attribute you would use

var strAttribute = $(".something").attr("title");

To set a single attribute you would use

$(".something").attr("title","Test");

set multiple个属性,您需要将所有内容包装在{…}

$(".something").attr( { title:"Test", alt:"Test2" } );

编辑-如果您试图从复选框中获取/设置"Checked"属性.

您需要使用prop() as of jQuery 1.6+

the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

...the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does

因此,对于复选框的get the checked status,您应该使用:

$('#checkbox1').prop('checked'); // Returns true/false

或设置为set the checkbox as checked or unchecked,您应该使用:

$('#checkbox1').prop('checked', true); // To check it
$('#checkbox1').prop('checked', false); // To uncheck it

Jquery相关问答推荐

TinyMCE不保存区块报价

如何使 Bootstrap 轮播滑块使用移动左/右滑动

可以推迟 jQuery 的加载吗?

jQuery 时间 Select 器

递归循环遍历对象(树)

我如何从 ACE 编辑器中获得价值?

使用 jQuery 发送 JSON 数据

jQuery UI 自动完成宽度未正确设置

jQuery计算所有文本字段中的值的总和

动画元素变换旋转

Select 除第一个之外的所有子元素

如何将文本从 div 复制到剪贴板

jQuery Select 器中前导冒号的目的是什么?

jquery 检测某些类的 div 已添加到 DOM

5秒后jQuery自动隐藏元素

AngularJS:使用 jQuery 更改时,ng-model 绑定不更新

jQuery attr 与props ?

jQuery .each() 索引?

如何在 DOM 中移动 iFrame 而不会丢失其状态?

Jquery 日期 Select 器 z-index 问题