简体   繁体   中英

dynamically find jquery element if exists

i have a function, where if called, will update another object if it exists. thing is, when the page is created the id is not known.

so, for example, heres my code:

$('.slides').on("slidestop", function() {
                    $this = $(this);
                    $.ajax({
                        url: "action.php?event=ITEM "+$this.attr("data-itemID") + " " + this.value+"&itemID="+$this.attr("data-itemID"),
                        type:'POST',
                        success: function(result){
                            //update brightness slider if it exists
                            $("#sl" + $this.attr('data-itemID')).val(15);
                            $("#sl" + $this.attr('data-itemID')).slider("refresh");
                        },
                    });
                });

html:

 <input class='dimmerSlider' type='range' id='3' value='4' min='0' max='15' step='1' data-highlight='true' data-itemID='3'/>

error:

Uncaught TypeError: $(...).slider is not a function

$("#$this.attr('data-itemID')").val(15);

I am guessing you wanted to build a string using the attibute

$("#" + $this.attr('data-itemID')).val(15);

or use data instead of attr

$("#" + $this.data('itemID')).val(15);

To answer your second question if the element can not be found.

If you select an element with jQuery and it does not exist, it will be ignored when you run methods against it. If you need to know it does not exist than you can check the length

var x = $(".mySelector");
if (!x.length) {  //aka x.length===0
   console.log("not found");
}

also, the element is not guaranteed to exist, how do i check for that as well?

Try using Attribute Equals Selector [name="value"] , .is()

  var elem = $("[id=" + $this.attr("data-itemID") + "]");
  if (elem.is("*")) {
    // do stuff
    elem.val(15)
    .slider("refresh");
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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