添加其他ID

时间:2018-10-18 23:59:19

标签: javascript jquery id

如何添加其他ID而不删除第一个ID

<div id="first-id"></div>

<div id="first-id second-id"></div>

2 个答案:

答案 0 :(得分:0)

您可以使用函数$.clone克隆元素,然后添加特定的ID。

var $cloned = $('#first-id').clone();
$cloned.attr('id', $cloned.attr('id') + ' second-id');
$cloned.html($cloned.attr('id'));

$('body').append($cloned);
console.log($cloned.get(0));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="first-id">first-id</div>

答案 1 :(得分:0)

我认为您的目的是识别其他自定义场景中的元素。为此,我们可以使用 jQuery

使用元素数据属性
<!DOCTYPE html>
<html>
<head>
    <title>test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="first-id" style="width:300px;height: 100px;background-color: #536dfe"></div>
</body>
</html>
<script type="text/javascript">

    $(document).ready(function () {

        // to SET the custom id
        $("#first-id").attr('data-second-id', 'second-id');

        // to GET the custom id
        console.log($("#first-id").attr('data-second-id'));

        //  even if you want object you can stringify that object and set the value using jquery;

        var obj = {"first": 'Some data 1', "second": 'Some data 2', "third": 'Some data 3'};

        $("#first-id").attr('data-custom-data-object', JSON.stringify(obj));
        console.log($("#first-id").attr('data-custom-data-object'));

        // to access the object values
        var get_data_object_values = JSON.parse($("#first-id").attr('data-custom-data-object'));
        var first = get_data_object_values.first;
        var second = get_data_object_values.second;
        var third = get_data_object_values.third;

        console.log(first);
        console.log(second);
        console.log(third);


    });
</script>

最后,如果要选择元素进行某种操作,则可以使用自定义属性

// will give you the width of the element 

 console.log($('*[data-second-id="second-id"]').css("width"))