简体   繁体   中英

having trouble to pass div ID as function parameter

I want to give user options to edit title of navigation bar. So, when user would click edit, I want to give them a text field and a submit button.

Here is the code(within PHP block)

$n1="<div  id='nava' class='nav' >
      <a href=#>$nava</a>
      <input type='submit' id='nav1' class='b' onclick='edit(this.id,???)' value='Edit'>
     </div>";
$n2="<div  id='navb' class='nav' >
      <a href=#>$navb</a>
      <input type='submit' id='nav2' class='b' onclick='edit(this.id,???)' value='Edit'>
     </div>";
$n3="<div  id='navc' class='nav' >
      <a href=#>$navc</a>
      <input type='submit' id='nav3' class='b' onclick='edit(this.id,???)' value='Edit'>
     </div>";

if I do edit(this.id,nava),it gives me object DivElement message,when I do alert.

But I need the id of div as string.Passing the id of submit button works perfectly, but I cannot figure out how to pass the id of corresponding div to edit function. How would I do that?

parentNode is definitely the right way to go about getting the parent Div's id (without using a framework like JQuery). You can read more about it here: https://developer.mozilla.org/en/docs/Web/API/Node.parentNode

Back to your example, you could simply write a JavaScript edit() function like so:

function edit(id) {
    var divId = document.getElementById(id).parentNode.id;
    console.log(divId);
}

Using your HTML, I have put together a quick fiddle for you to show how this can work

http://jsfiddle.net/wj7bch3m/

Hope that helps!

You could do something like this to change the different navs

html

<div id="nav">
    <a href="#" id="link1">Link</a>
    <input type="text" for="link1" id="newLink" class="changeNav"/>
</div>

jquery

$(".changeNav").on("change", function(){
    var newLink = $(this).val();
    var whichNav = $(this).attr("for");
    $("#" + whichNav).empty().append(newLink);
});

here is a JSFIDDLE

Hope this helps

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