我试图用js获取某些链接的值,但每次我收到警报:未定义。
我尝试了很多东西,但没有任何东西对我有用:(也许你们中的一些人可以帮助我???
代码:
function protected_link() {
var pass1 = prompt("Wachtwoord!!!");
var pass2 = "admin";
var kerntaak = $(this).attr("id");
if (pass1 === pass2) {
load('img/pdf/'+kerntaak+'.pdf')
} else {
load('index.php')
}
}
这是一些<a>
我的链接:
<a value="kerntaak1" onclick="protected_link();" class="btn btn-primary btn-lg flex-item page-scroll"" style="letter-spacing: 5px";>kerntaak 1</a>
最佳答案
您正在调用 protected_link(this.id);
,但没有上下文(这将是 foo.protected_link
或通过 .call() 提供
或 .apply()
)。
所以在函数内部 this
将是 window
。
毫不奇怪,$(window).attr("id")
不会为您提供您想要的值。
您将 id 作为参数传递:
protected_link(this.id);
^^^^^^^
...所以使用它。
function protected_link(kerntaak) {
alert(kerntaak);
更正。您已编辑问题。您将其作为参数传递。然后你就把它删除了。取消删除它。把它放回去。
<小时/>如果您正在编写现代 JavaScript,则不会使用内部事件属性,您可以这样做:
$("some selector that matches the elements you care about")
.on("click", protected_link);
(我使用 jQuery 进行事件绑定(bind),因为您已经在使用它)
这将在元素的上下文中调用,并且 this
将是函数内的元素。
关于javascript - 使用 JS 从 <a> 链接获取 ID 或 VALUE 或 NAME,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38064138/