简体   繁体   English

将JQuery变量设置为HTML元素属性子字符串

[英]Setting JQuery Variable to HTML Element Attribute Substring

I'd like to set a variable to equal the text of a substring. 我想将变量设置为等于子字符串的文本。 Specifically, if a[href] begins with "download.php", I'd like to set the variable "elm" to the value of a[href], after the 19th character. 具体来说,如果[href]以“download.php”开头,我想在第19个字符后面将变量“elm”设置为[href]的值。

if ("a[href^='download.php']") {
    var elm = $('a[href]'.substring(19));
};

I've tried using .text() and .html(), but can't get it working. 我尝试过使用.text()和.html(),但无法使用它。 Can someone point out my errors? 有人可以指出我的错误吗? Many thanks. 非常感谢。

You dont need your if statement, since you are passing a string which is a truthy value. 你不需要你的if语句,因为你传递的是一个真正的值的字符串。

To get the value of href atributte use $.attr 要获得href atributte的值,请使用$ .attr

var elm = $("a[href^='download.php']").attr('href').substring(19);

and if you want to check if exists any element who match with [href^='download.php'] use 如果你想检查是否存在任何与[href^='download.php']匹配的元素

var el = $("a[href^='download.php']");
if(el.length) {
    var elm = el.first().attr('href').substring(19);
}
var a = $("a[href^='download.php']");
if (a.length) {
  var elm = a.attr("href").substring(19);
}

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

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