问题 如何将自定义属性添加到并在JavaScript中读取? [重复]


这个问题在这里已有答案:


8428
2018-06-18 01:11


起源



答案:


使用data- *属性。像data-href这样的东西会很好。 jQuery为您提供了一个很好的界面来读取值。

this.data('href')

将读取的价值

data-href="some.value"

看到 http://api.jquery.com/jquery.data/ 更多。


7
2018-06-18 01:13



你究竟会怎么做?我对这种东西很陌生。 - RetroCraft
添加了一个例子 - James Mason


答案:


使用data- *属性。像data-href这样的东西会很好。 jQuery为您提供了一个很好的界面来读取值。

this.data('href')

将读取的价值

data-href="some.value"

看到 http://api.jquery.com/jquery.data/ 更多。


7
2018-06-18 01:13



你究竟会怎么做?我对这种东西很陌生。 - RetroCraft
添加了一个例子 - James Mason


您可以使用 data-。因此,在HTML中,您可以将其定义为:

<span class="navLink" data-link="google.com">click me</span>

然后通过jQuery你只需:

window.location.href = "/index.php?page=" + $(this).data("link");

3
2018-06-18 01:18





纯粹的js:

el.setAttribute('value', the-value);

jQuery的:

$(el).attr('value', the-value);

但更好的做一些容易识别的东西 my-value 作为属性的名称,以避免冲突并使其更容易在代码中注意到


1
2018-06-18 01:14