简体   繁体   English

jQuery:选择具有唯一类和ID的元素

[英]JQuery: Selecting elements with unique class AND id

I have this html code: 我有这个HTML代码:

<div class="category" id="154"> Category </div>

<div class="category2" id="156"> Category2 </div>

<div class="category3" id="157"> Category3 </div>

<div class="category4" id="158"> Category4 </div>
<input type="text" />

So in example if I write a id in text box, how to select div .category with this ID and get inner HTML text. 因此,在示例中,如果我在文本框中编写一个ID,则如何使用该ID选择div .category并获取内部HTML文本。 With jQuery 用jQuery

so you only need to use the ID as this is a unique value (or should be) 所以您只需要使用ID,因为这是一个唯一值(或应该是)

var html = $("#154").html();

NOTE : If you do have duplicate ID values in use then it is important to note that JQuery will only select the first one. 注意 :如果确实使用了重复的ID值,则需要注意的是,JQuery将仅选择第一个。


if you want to do this when a textbox value is entered you could do this on the textbox change event... 如果要在输入文本框值时执行此操作,可以在文本框更改事件中执行此操作...

$("input").change(function(){
   var id = $(this).val();
   var element = $("#" + id);
   if(element){
      var html = element.html();
      //do something with html here
   }
});

NOTE : you may want to put an ID value on your textbox to ensure you get the correct control 注意 :您可能希望在文本框中输入一个ID值,以确保获得正确的控件


Although I strongly suggest you find a way around using duplicate ID values, you could have a function like this to get the DIV you want... 尽管我强烈建议您找到一种使用重复ID值的方法,但是您可以使用类似的功能来获取所需的DIV。

function GetContent(className, id) {
    var result = null;
    var matchingDivs = $("." + className);
    matchingDivs.each(function(index) {
        var div = $(matchingDivs[index]);
        if (div.attr("id") == id) {
            result = div.html();
        }
    });

    return result;
}

Click here for working example 单击此处查看工作示例

I recommend you give the textbox an ID, in case you add other textboxes to the page. 我建议您为文本框指定一个ID,以防在页面上添加其他文本框。

But if you only have the 1 text input, the following would work: 但是,如果您仅输入1个文本,则可以使用以下内容:

 var id = $('input:text:first').val();
 var innerHtml = $('#' + id).html();

Here is a jsFiddle that will alert the html using this technique whenever the text in the textbox changes. 这是一个jsFiddle ,它将在文本框中的文本更改时使用此技术来警告html。

$("#id.class")

will select the necessary element by both class and ID (replacing id and class with their respective names, of course). 会同时通过class和ID选择必要的元素(当然,请使用各自的名称替换idclass )。

Adding .html() to the end will get you the content. 在末尾添加.html()将获得内容。

ie: 即:
$("#id.class").html()

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

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