gpt4 book ai didi

javascript - 单击使用这些 id 在 javascript 中获取此变量

转载 作者:行者123 更新时间:2023-11-29 23:54:33 24 4
gpt4 key购买 nike

单击 h2 时,我需要在 javascript 的这两个位置使用此变量 $post_id,就像我在 html 中添加了 img 和 input 一样。

如何在 javascript 中获取此变量并添加这两个 ID?

<h2  id="view" data-target="#Modal_<?php echo $post_id;?>"> view  </h2>

<img id="pic<?php echo $post_id; ?> " />

<input id="input<?php echo $post_id; ?>" >

js:

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();

reader.onload = function (e) {
$('#pic').attr('src', e.target.result); // here with #pic
}

reader.readAsDataURL(input.files[0]);

}
}

$("#input").change(function(){ // here with #input
readURL(this);
});

更新:

点击 li 时更改 id。

 <li data-toggle="modal" data-target="#myModal_<?php echo $post_slug;?>"><a>View</a></li>

<div id="myModal_<?php echo $post_slug;?>" >


<input type="file" class="file" id="imgInp<?php echo $post_slug;?>"/>

<img id="blah<?php echo $post_slug;?>" />

</div>

js:

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();

reader.onload = function (e) {
$('#blah').attr('src', e.target.result); // here in id add this blah<?php echo $post_slug;?>
}

reader.readAsDataURL(input.files[0]);

}
}

$("#imgInp").change(function(){ // here in id add this imgInp<?php echo $post_slug;?>
readURL(this);
});

最佳答案

您必须将点击事件添加到h2,然后使用jQuery 方法 .data() 获取data-target 并使用 split() 方法从中提取 post_id 然后将 id 设置为 img/input 使用 .prop() 方法:

$("h2").on('click', function(){
var target = $(this).data('target');

$('img').prop('id', 'pic'+target);
$('input').prop('id', 'input'+target);
});

您还应该调整其他事件/函数来处理动态id,例如:

function readURL(input, post_id) {
if (input.files && input.files[0]) {
var reader = new FileReader();

reader.onload = function (e) {
$('#pic'+post_id).attr('src', e.target.result);
}

reader.readAsDataURL(input.files[0]);
}
}

// here with all inputs that has the 'id' start with 'input'
$("input[id^='input']").change(function(){
var post_id = $(this).prop('id').split('input')[1];
readURL(this, post_id);
});

希望这对您有所帮助。

$("h2").on('click', function(){
var target = $(this).data('target');
var post_id = target.split('_')[1]; //Remove the #Modal_

console.log('---Before', $('img').prop('id'), $('input').prop('id'));

$('img').prop('id', 'pic'+post_id);
$('input').prop('id', 'input'+post_id);

console.log('---After', $('img').prop('id'), $('input').prop('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2 id="view" data-target="#Modal_100"> view </h2>
<img id="pic" />
<input id="input" />

关于javascript - 单击使用这些 id 在 javascript 中获取此变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41999507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com