jQuery change id!
I am a jQuery noobie, and have been trying to add a s开发者_JAVA技巧cript to change the id of a div onClick.
Here is a jsfiddle example.
$(function accept() {
$("div:scrollwrap").attr('scrollwrap','highlight');
});
Thanks :)
The first parameter of attr
should be the attribute name, not the current value:
$(function accept() {
$("div#scrollwrap").attr('id','highlight');
});
However, reading your jsFiddle code, you appear to have a class of highlight and not an ID. Here is my edited version with what I think you are trying to achieve.
Note that I have changed the following:
- Made the .hightlight class more specific by adding the ID, otherwise the highlight style will not override the original.
- Removed the inline onClick as you can do this within your script, which is considered best practice (see JS for the
.click()
addition) - Changed the JS function to toggle the class, as I assume it should be invalidated if the user deselects the checkbox.
More resources (jQuery docs):
- .toggleClass()
- .click()
- .attr()
if you want to change the div with the id scrollwrap to have the id highlight:
$(document).ready(function() {
$("#checkbox2").click(function() {
$("#scrollwrap").attr('id','highlight');
});
});
remember an ID is unique, so this should only affect one element. if you want to affect multiple use classes and the functions .addClass()/.removeClass()
this is how you change a ID:
$(function accept(){ //makes sure your document is ready
$('div#scrollwrap').attr('id', 'highlight')
})
(i assume scrollwram is you ID)
精彩评论