简体   繁体   English

jQuery从html标记中提取属性ID

[英]jQuery extracting attribute id from html tag

I'm using a piece of code that is supposed to extract the value from a tag in html. 我正在使用一段应该从html中的标记中提取值的代码。 It works fine with a single word for example 'desk' but it doesn't work with an id composed by two or more words: <a href='#' id='hello world'> Hello world </a> 它可以很好地使用单个单词(例如“ desk”),但不能使用由两个或多个单词组成的ID: <a href='#' id='hello world'> Hello world </a>

In this cases I'm only getting the word 'hello' and not 'hello world'. 在这种情况下,我只会得到“ hello”一词,而不是“ hello world”。 Here's my code: 这是我的代码:

 $('ul').on('click', 'li', function(){ 
            var id = $(this).attr('id');
            console.log(id);
     });

Is there any way to extract a multiple word id? 有什么方法可以提取多个单词的ID? Thanks. 谢谢。

The id attribute cannot contain spaces according to the spec , but even if it could, the data-* attribute is a better place to store generic data. 根据规范id属性不能包含空格,但是即使可以, data-*属性还是存储通用数据的更好位置。 id s are used for identifying elements. id s用于标识元素。

html: 的HTML:

<li data-value="hello world"></li>

js: js:

$('ul').on('click', 'li', function(){ 
    var val = $(this).data('value');
    console.log(val);
});

ID only supports one value. ID仅支持一个值。 In that case, use a class. 在这种情况下,请使用一个类。

ID should be a unique value, and thus only have one value in it. ID应该是唯一值,因此其中只有一个值。 Using spaces is bad, I would replace them with underscores. 使用空格是不好的,我用下划线代替它们。 If you need multiple values, you'll probably want to use classes instead. 如果需要多个值,则可能要使用类。

However, this works like you are asking for. 但是,这就像您所要求的那样。

HTML: HTML:

<li id='hello_world'> Hello world </li>

JS: JS:

$('li').on('click', function(){ 
        var id = $(this).attr('id');
        alert(id);
});

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

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