Is there any way to use a JS variable as input instead of jquery selector “#id”?

孤街醉人 提交于 2020-01-17 09:20:03

问题


I want to know that, can we able to give a variable instead of #anyId inside a selector.

Actually i am trying this code,

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="aDiv123">
  <p id="abcd1234" class="abcd123">Click me!</p>
</div>

<script>
    $("p").live("click", function() {
        $(this).after("<p id='abcd123' class='abcd2323'>Another paragraph!</p>");
        var number = this.id.match(/^abcd(\d+)$/)[1];
        var iD = this.id;
        alert(number);
        alert(iD);
        var div = "#"+"aDiv"+number;
        alert(div)
        $(div).remove();
    });
</script>

</body>
</html>

This is the fiddle link for the above code.

Any suggestions about where i am doing it wrong!!!!

Thanks!


回答1:


The problem is that your Div has a different number from the paragraph, it should be:

<div id="aDiv1234">
<p id="abcd1234">

Not: aDiv123




回答2:


Yes you can use a variable, assuming it contains a string that is a valid jquery selector, or a reference to a DOM element, or a reference to another jquery object.

The jquery api documentation is excellent if you're getting stuck with jquery usage.

http://api.jquery.com/jQuery/




回答3:


I believe your problem is just a typo. You have elements with IDs #aDiv123 and #abcd1234, but trying to remove #aDiv1234. Correct this and it will work.




回答4:


The $ JQuery function only takes a string for parameter, so you can build your own selector passing by some variables.

var sel = tag + ':visible';
$(sel) -> all visible "tags"



回答5:


If you want to do an operation on the div which contains the paragraph, why not instead do:

$('p').live('click', function() {
  $(this).parent().remove();
});

... or ...

$('p').live('click', function() {
  $(this).parents('.discriminator').remove();
});


来源:https://stackoverflow.com/questions/4076570/is-there-any-way-to-use-a-js-variable-as-input-instead-of-jquery-selector-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!