我只是简单地说明了一点。这里是MySQL数据库的示例表。什么是识别HTML元素的最佳方法
SQL数据库
+----+-------------+
| ID | Description |
+----+-------------+
| 1 | Example 1 |
| 2 | Example 2 |
| 3 | Example 3 |
| 4 | Example 4 |
+----+-------------+
然后我使用PHP(Laravel框架)来从数据库中的数据得到我的观点。
Laravel
@foreach
<div id="entry_{{ $table->id }}">
<input type="text" id="description_{{ $table->description }}">
<button id="save_{{ $table->id }}" class="button">Save</button>
<button id="delete_{{ $table->id }}" class="button">Delete</button>
</div>
@endforeach
现在我们必须在HTML视图整个数据库的内容。为了更好的用户体验,我需要使用jQuery进行技巧提示,因此我检查是否有任何按钮被按下。
jQuery的
$(document).ready(function()
{
$(".button").click(function()
{
// Get's id of button what is pressed
var elementID = this.id;
// I don't know if this regexp works, but you get the point.
// Let's grab all text before and after _
var regexp = /(.*?)_(.*?)/;
var match = elementID.match(regexp);
var operation = match[1];
var id = match[2];
// And here i would check that is operation save or delete.
// If it is delete_2, i would do tricks with AJAX and after that delete div entry_2
});
});
我的问题是有没有命名/识别HTML元素,这样我就不必使用正则表达式和匹配一些小把戏更好的办法?这工作,我用这个,但如果有更好的方式,我想学习它。
这一工程,但我会用'的正则表达式匹配this.id.split( “_”)'代替。或者,您可以使用'data-action =“delete”data-id =“2”'属性。 –