gpt4 book ai didi

javascript - jQuery : How do I get the current id of the element I have clicked on and change it’s name?

转载 作者:行者123 更新时间:2023-11-28 05:14:18 25 4
gpt4 key购买 nike

我有一个拖放网站构建器,它使用 html block ,每个 block 都有一个设置的 id。将 block 拖放到 Canvas 上后,我需要创建一个链接到每个 block 的 id 的导航菜单。如何获取我点击的 block 的当前 ID 并更改其名称?

以下是我尝试过的方法,但有一些问题:

  1. 它不显示 block 的名称
  2. 它只接受整数(当我输入文本时给出 NaN)
  3. 它会更改 Canvas 上所有 block 的 ID,而不仅仅是更改我单击的 block 的 ID

.

PHP 页面 (index.php)

  <div class="setting opt">
<div class="dropdown">
<a class="icons" data-toggle="dropdown" href="#settings"></a>
<ul class="dropdown-menu ">
<li><a href="#" id="blockName" tabindex="-1">Edit Block Name</a></li>
</ul>
</div>
</div>
<section class="builder_block" id="header_2"></section>
<section class="builder_block" id="content_5"></section>
<section class="builder_block" id="footer_9"></section>

Jquery 页面(editor.js)

$(document).on("click", "#blockName", function(e) {
e.preventDefault(),toastr.info("Block Renamed.");
var bname = prompt("Please enter your new block name");
var myblockName = $("section.builder_block").attr("id", +bname);
});

最佳答案

在jquery中,你可以使用:

$(this).attr('id', [new-value]);

工作示例:

$(document).ready(function(){

$('div[id^="block-"]').click(function(){
$(this).attr('id','new-' + $(this).attr('id'));
$(this).html($(this).html().replace('block','new-block'));
});

});
div {
display: inline-block;
margin: 6px;
padding: 6px;
color: rgb(255,255,255);
background-color: rgb(255,0,0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="block-1">My <em>id</em> is <strong>block-1</strong></div>
<div id="block-2">My <em>id</em> is <strong>block-2</strong></div>
<div id="block-3">My <em>id</em> is <strong>block-3</strong></div>

单击示例中的每个框可检索 divid 并将其替换为新的更新的 id

<小时/>

这是原生的 javascript 版本,因此您可以与上面的 jQuery 进行比较和对比:

var blocks = document.querySelectorAll('div[id^="block"]');

function updateId() {
var id = this.id;
id = id.replace('block','new-block');
this.id = id;

var html = this.innerHTML;
html = html.replace('block','new-block');
this.innerHTML = html;
}

for (var i = 0; i < blocks.length; i++) {
blocks[i].addEventListener('click',updateId,false);
}
div {
display: inline-block;
margin: 6px;
padding: 6px;
color: rgb(255,255,255);
background-color: rgb(255,0,0);
}
<div id="block-1">My <em>id</em> is <strong>block-1</strong></div>
<div id="block-2">My <em>id</em> is <strong>block-2</strong></div>
<div id="block-3">My <em>id</em> is <strong>block-3</strong></div>

关于javascript - jQuery : How do I get the current id of the element I have clicked on and change it’s name?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41109574/

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