简体   繁体   中英

Changing a div's id in order to show/hide

My old code looked like this:

function unhide(rad) {
var id = "answer" + rad.id.replace("-", "");
var answer = document.getElementById(id);
if (answer) {
    var current = document.getElementById(currentShown);
    if (current) current.className = "hidden";
    currentShown = id;
    answer.className = "unhidden";
}
}

When my radio button was clicked:

<input class="editable" type="radio" name="q1" id="q1-a" onclick="unhide(this); scoreIncrement(this);"/>John

It would unhide this div:

<div id="answerq1a" class="hidden">
<p>Your answer is correct, John is 6ft2.</p>
</div>

But now, my radio button must look like this:

<input class="editable" type="radio" name="q1" id="untitled-region-1" onclick="unhide(this); scoreIncrement(this);"/>John

and my div that I want to unhide has the same id, but as they are unique, it replaces the 1 with the next number up. In my case it is 4 id's down so the id would be "untitled-region-5" for the new id, as follows:

<div id="untitled-region-5" class="hidden">
<p>Your answer is correct, John is 6ft2.</p>
</div>

So how can I change this code, to grab the new id "untitled-region-5" and minus 4 from it to fix it to the radio button with the new id's?

function unhide(rad) {
var id = "answer" + rad.id.replace("-", "");
var answer = document.getElementById(id);
if (answer) {
    var current = document.getElementById(currentShown);
    if (current) current.className = "hidden";
    currentShown = id;
    answer.className = "unhidden";
}
}

I am going along this sort of track:

function unhide2(rad) {
var id = $("div").attr('id').replace(/untitled-region-/, 'untitled-region-');
var untitled-region = document.getElementById(id);
if (untitled-region) {
    var current = document.getElementById(currentShown);
    if (current) current.className = "hidden";
    currentShown = id;
    untitled-region.className = "unhidden";
}
}

But I don't know how to replace the last digit on the id with "digit-4".

You've tagged this with jQuery, so I'll give you the jQuery answer.

The right way to solve this is not to mash about with id's, but to link the radio, and it's associated div some other way, and IMO the best way is using a data- attribute.

<input class="editable" type="radio" 
   name="q1" id="q1-a" data-answerId="untitled-region-5"/>John

Then your javascript becomes easy-as:

$('.editable').click(function(){
   $('#' + currentShown).removeClass('unhidden').addClass('hidden');
   var answerId = $(this).data('answerId');
   $('#' + answerId).removeClass('hidden').addClass('unhidden');
});

Although I urge you to do away with the unhidden , hidden confusion and just use .show() and .hide() !

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