Is there any way to use a JS variable as input instead of jquery selector "#id"?
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!
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/
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.
The problem is that your Div has a different number from the paragraph, it should be:
<div id="aDiv1234">
<p id="abcd1234">
Not: aDiv123
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"
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();
});
精彩评论