当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Multiple ID's on single button click

问题描述:

HTML + PHP

<?php

for($i=0;$i<5;$i++){

?>

<input readonly class="copyTarget" id="copyTarget<?php echo $i; ?>" value="val<?php echo $i; ?>">

<span>

val<?php echo $i; ?>

</span>

<button class="btn btn-primary" id="copyButton<?php echo $i; ?>" onClick="reply_click(this.id, $('.copyTarget').attr('id'));">Copy</button>

<?php

}

?>

JS

<script>

function reply_click(clicked_id, target_id) {

alert(clicked_id);

alert(target_id);

}

</script>

What i want

I want to get the both values for copyTarget and copyButton as per loop cycle. It means

If current value of $i = 3

then I want alert values like,

clicked_id = copyTarget3

target_id = copyButton3

What i am currently getting is,

If current value of

$i = 3

then I want alert values like,

clicked_id = copyTarget0

target_id = copyButton3

Its taking first value of ID(copyTarget) stored initially. I want current loop cycle value.

Any help would do

Thanks

网友答案:

Why use JS in handler?

Try:

onClick="reply_click('copyButton<?php echo $i; ?>', 'copyTarget<?php echo $i; ?>')"

Also you should store id names (copyButton and copyTarget) in php variable, so you can change them in one place.

网友答案:

You could try something like below. However, I would go by Maxx's answer .. It really depends on what you plan to do with the rest of code etc.

<?php
  for($i=0;$i<5;$i++){
?>

<div>
    <input readonly class="copyTarget" id="copyTarget<?php echo $i; ?>" value="val<?php echo $i; ?>">
    <span>
      val<?php echo $i; ?>
    </span>

    <button class="btn btn-primary" id="copyButton<?php echo $i; ?>"  onClick="reply_click(this)">Copy</button> 
</div>

<?php
  }
?>

<script>
function reply_click(btn) {
    var clicked_id = $(btn).attr('id');
    var target_id=$(btn).parent().find('span').html();

    alert(clicked_id);
    alert(target_id);
}
</script>
网友答案:

Try This

<?php
 for($i=0;$i<5;$i++){
 ?>

 <input readonly class="copyTarget" id="copyTarget<?php echo $i; ?>" value="val<?php echo $i; ?>">

 <span>
   val<?php echo $i; ?>
 </span>

 <button class="btn btn-primary" id="copyButton<?php echo $i; ?>"   onClick="reply_click(this.id);">Copy</button>


<?php
 }
?>

JS

<script>
function reply_click(clicked_id) {
    alert(clicked_id); //clicked id
    alert(clicked_id.split('copyButton').join('copyTarget')); // target id
}
</script>
分享给朋友:
您可能感兴趣的文章:
随机阅读: