Добавить новый элемент в массив без указания индекса в Bash

Массивы — это фундаментальная структура данных в программировании, которая позволяет нам хранить несколько значений и управлять ими под одним именем переменной. В Bash массивы являются неотъемлемой частью сценариев оболочки, что позволяет нам эффективно выполнять широкий спектр операций. Одной из основных операций при работе с массивами является добавление нового элемента в массив без указания индекса. В этой статье мы рассмотрим, как добавить новый элемент в массив без указания индекса в Bash.

Добавление нового элемента в массив без указания индекса в Bash

Добавление нового элемента в массив без указания индекса — простая задача в Bash. Мы можем добиться этого, используя оператор += с именем массива и новым значением, которое мы хотим добавить. Вот синтаксис добавления нового элемента в массив без указания индекса:

<array-name>+=<new-element>

Здесь <имя-массива> — это имя массива, в который мы хотим добавить новый элемент, а <новый-элемент> — это значение, которое мы хотим добавить в массив, здесь я привел пример, чтобы лучше понять это. :

#!/bin/bash

# Declare an array

array=(Red Orange Pink)

echo “Original Array:” ${array[@]}

# Add a new element to the array

array+=(Yellow)

# Print the array

echo “Updated Array:” ${array[@]}

В приведенном выше примере мы объявили массив с именем array с тремя элементами Red, Orange и Pink. Затем мы добавили в массив новый элемент Yellow с помощью оператора +=. Наконец, мы напечатали массив, используя синтаксис ${array[@]}. Как видите, дата нового элемента добавлена ​​в конец массива.

Автоматически сгенерированное текстовое описание

Заключение

В этой статье мы рассмотрели, как добавить новый элемент в массив без указания индекса в Bash. Мы видели, что это простая задача, которую можно выполнить, используя оператор += с именем массива и новым значением, которое мы хотим добавить. Следуя приведенным выше шагам, мы можем эффективно добавлять новые элементы в массив без указания индекса в Bash.

Оригинальный источник статьи: https://linuxhint.com/

#bash #element #array #without 

Добавить новый элемент в массив без указания индекса в Bash
佐藤  桃子

佐藤 桃子

1684135380

在不指定 Bash 中的索引的情况下向数组添加新元素

数组是编程中的一种基本数据结构,它允许我们在单个变量名下存储和操作多个值。在 Bash 中,数组是 shell 脚本的重要组成部分,它使我们能够高效地执行各种操作。使用数组时的基本操作之一是在不指定索引的情况下向数组添加新元素。在本文中,我们将探讨如何在 Bash 中不指定索引的情况下向数组添加新元素。

在不指定 Bash 中的索引的情况下向数组添加新元素

在不指定索引的情况下向数组添加新元素在 Bash 中是一项简单的任务。我们可以通过将 += 运算符与数组名称和我们要添加的新值一起使用来实现这一点。以下是在不指定索引的情况下向数组添加新元素的语法:

<array-name>+=<new-element>

这里,<array-name> 是我们要添加新元素的数组的名称,<new-element> 是我们要添加到数组的值,这里我举了一个例子来更好地理解这一点:

#!/bin/bash

# Declare an array

array=(Red Orange Pink)

echo “Original Array:” ${array[@]}

# Add a new element to the array

array+=(Yellow)

# Print the array

echo “Updated Array:” ${array[@]}

在上面的示例中,我们声明了一个名为 array 的数组,其中包含三个元素 Red、Orange 和 Pink。然后,我们使用 += 运算符向数组添加了一个新元素 Yellow。最后,我们使用 ${array[@]} 语法打印了数组。如您所见,新元素 date 已添加到数组的末尾。

文本描述自动生成

结论

在本文中,我们探讨了如何在 Bash 中不指定索引的情况下向数组添加新元素。我们已经看到这是一个简单的任务,可以使用 += 运算符和数组名称以及我们要添加的新值来完成。通过以上步骤,我们可以高效地向数组添加新元素,而无需在 Bash 中指定索引。

文章原文出处:https: //linuxhint.com/

#bash #element #array #without 

在不指定 Bash 中的索引的情况下向数组添加新元素

Add a New Element to an Array Without Specifying the Index in Bash

Arrays are a fundamental data structure in programming that allow us to store and manipulate multiple values under a single variable name. In Bash, arrays are an essential part of shell scripting, allowing us to perform a wide range of operations efficiently. One of the essential operations when working with arrays is adding a new element to an array without specifying the index. In this article, we will explore how to add a new element to an array without specifying the index in Bash.

Adding a new element to an array without specifying the index in Bash

Adding a new element to an array without specifying the index is a straightforward task in Bash. We can achieve this by using the += operator with the name of the array and the new value we want to add. Here is the syntax for adding a new element to an array without specifying the index:

<array-name>+=<new-element>

Here, <array-name> is the name of the array to which we want to add a new element, and <new-element> is the value we want to add to the array, here I have given an example to understand this better:

#!/bin/bash

# Declare an array

array=(Red Orange Pink)

echo “Original Array:” ${array[@]}

# Add a new element to the array

array+=(Yellow)

# Print the array

echo “Updated Array:” ${array[@]}

In the above example, we have declared an array called array with three elements Red, Orange, and Pink. Then, we added a new element Yellow to the array using the += operator. Finally, we have printed the array using the ${array[@]} syntax. As you can see, the new element date has been added to the end of the array.

Text Description automatically generated

Conclusion

In this article, we have explored how to add a new element to an array without specifying the index in Bash. We have seen that it is a straightforward task that can be accomplished using the += operator with the name of the array and the new value we want to add. By following the above steps, we can efficiently add new elements to an array without specifying the index in Bash.

Original article source at: https://linuxhint.com/

#bash #element #array #without 

Add a New Element to an Array Without Specifying the Index in Bash

Замените класс элемента CSS с помощью JavaScript

Метод replace() свойства classList может заменить класс CSS из элемента HTML в JavaScript.

Допустим, у вас есть следующий элемент HTML:

<div class="pizza spicy hot crispy">🍕</div>

Чтобы заменить пряный класс на оливковый , вы можете сделать следующее:

const div = document.querySelector('div')

div.classList.replace('spicy', 'olive')

Метод replace() возвращает true , если класс успешно заменен новым классом. В противном случае возвращается false .

В отличие от методов add() , remove() и toggle() свойства classList , метод replace() не работает в IE. Вы можете использовать его только в современных браузерах.

Взгляните на эту статью , чтобы узнать больше о добавлении, удалении и переключении классов CSS в JavaScript.

Оригинальный источник статьи: https://attacomsian.com/

#javascript #css #element 

Замените класс элемента CSS с помощью JavaScript
佐藤  桃子

佐藤 桃子

1682652120

使用 JavaScript 替换元素的 CSS 类

classList属性的replace ()方法可以从 JavaScript 中的 HTML 元素替换 CSS 类。

假设您有以下 HTML 元素:

<div class="pizza spicy hot crispy">🍕</div>

要将spicy类替换为olive类,您可以执行以下操作:

const div = document.querySelector('div')

div.classList.replace('spicy', 'olive')

如果类成功替换为新类,则replace ()方法返回true 。否则,返回false 。

与classList属性的add()remove()toggle()方法不同,replace()方法在 IE 中不起作用。您只能在现代浏览器中使用它。

查看本文,了解有关在 JavaScript 中添加、删除和切换 CSS 类的更多信息。

文章原文出处:https: //attacomsian.com/

#javascript #css #element 

使用 JavaScript 替换元素的 CSS 类

Replace A CSS Class Of an Element using JavaScript

The replace() method of the classList property can replace a CSS class from an HTML element in JavaScript.

Let us say you have the following HTML element:

<div class="pizza spicy hot crispy">🍕</div>

To replace the spicy class with the olive class, you can do the following:

const div = document.querySelector('div')

div.classList.replace('spicy', 'olive')

The replace() method returns true if the class is successfully replaced with the new class. Otherwise, false is returned.

Unlike add(), remove(), and toggle() methods of the classList property, the replace() method doesn't work in IE. You can only use it in modern browsers.

Take a look at this article to learn more about adding, removing, and toggling CSS classes in JavaScript.

Original article source at: https://attacomsian.com/

#javascript #css #element 

Replace A CSS Class Of an Element using JavaScript

Получить идентификатор элемента с помощью jQuery

В этой статье мы увидим, как получить идентификатор элемента с помощью jquery. Использование метода jquery attr() для получения или установки значения атрибута id элемента. Метод attr() устанавливает или возвращает значения атрибутов выбранных элементов.

Итак, давайте посмотрим, как получить идентификатор щелкнутого элемента jquery, jquery получить идентификатор элемента, установить идентификатор элемента jquery, метод attr в jquery, как получить идентификатор элемента в javascript, получить идентификатор элемента при нажатии jquery, установить значение атрибута jquery.

В следующем примере идентификатор элемента DIV будет отображаться в окне предупреждения при нажатии кнопки.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>How To Get The ID Of An Element Using jQuery - Websolutionstuff</title>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <style>
            div{
                padding: 20px;
                background: #abb1b8;
            }
        </style>
        <script>
        $(document).ready(function(){
            $("#btnID").click(function(){
                var elmId = $("#divID").attr("id");
                alert(elmId);
            });
        });
        </script>
    </head>
    <body>
        <div id="divID">#text</div><br>
        <button type="button" id="btnID">Show Div ID</button>
    </body>
</html>

Вы также можете получить идентификатор нескольких элементов, имеющих один и тот же класс, через цикл, как это.

<!DOCTYPE html>
<html lang="en">
    <head>
    <title>How To Get The ID Of An Element Using jQuery - Websolutionstuff</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <style>
        div{
            padding: 20px;
            margin-bottom: 10px;
            background: #abb1b8;
        }
    </style>
    <script>
    $(document).ready(function(){
        $("#btnID").click(function(){
            var idArr = [];
            $(".box").each(function(){
                idArr.push($(this).attr("id"));
            });
            
            // Join array elements and display in alert
            alert(idArr.join(", "));
        });
    });
    </script>
    </head>
    <body>
        <div class="box" id="divIDOne">#boxOne</div>
        <div class="box" id="divIDTwo">#boxTwo</div>
        <div class="box" id="divIDThree">#boxThree</div>
        <button type="button" id="btnID">Show ID List</button>
    </body>
</html>

Оригинальный источник статьи: https://websolutionstuff.com/

#jquery #element #id 

Получить идентификатор элемента с помощью jQuery
木村  直子

木村 直子

1682067720

使用 jQuery 获取元素的 ID

在本文中,我们将看到如何使用 jquery 获取元素的 id。使用 jquery attr() 方法获取或设置元素的 id 属性值。attr() 方法设置或返回被选元素的属性值。

那么,让我们看看获取点击元素的id jquery,jquery获取元素的id,设置元素的id jquery,jquery中的attr方法,如何在javascript中获取元素的id,点击jquery获取元素的id,设置 attr 值 jquery。

以下示例将在单击按钮时在警告框中显示 DIV 元素的 ID。

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>How To Get The ID Of An Element Using jQuery - Websolutionstuff</title>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <style>
            div{
                padding: 20px;
                background: #abb1b8;
            }
        </style>
        <script>
        $(document).ready(function(){
            $("#btnID").click(function(){
                var elmId = $("#divID").attr("id");
                alert(elmId);
            });
        });
        </script>
    </head>
    <body>
        <div id="divID">#text</div><br>
        <button type="button" id="btnID">Show Div ID</button>
    </body>
</html>

您还可以通过循环获取具有相同类的多个元素的 ID,就像这样。

<!DOCTYPE html>
<html lang="en">
    <head>
    <title>How To Get The ID Of An Element Using jQuery - Websolutionstuff</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <style>
        div{
            padding: 20px;
            margin-bottom: 10px;
            background: #abb1b8;
        }
    </style>
    <script>
    $(document).ready(function(){
        $("#btnID").click(function(){
            var idArr = [];
            $(".box").each(function(){
                idArr.push($(this).attr("id"));
            });
            
            // Join array elements and display in alert
            alert(idArr.join(", "));
        });
    });
    </script>
    </head>
    <body>
        <div class="box" id="divIDOne">#boxOne</div>
        <div class="box" id="divIDTwo">#boxTwo</div>
        <div class="box" id="divIDThree">#boxThree</div>
        <button type="button" id="btnID">Show ID List</button>
    </body>
</html>

原文出处:https: //websolutionstuff.com/

#jquery #element #id 

使用 jQuery 获取元素的 ID
Gordon  Murray

Gordon Murray

1682060418

Get The ID Of An Element Using jQuery

In this article, we will see how to get the id of an element using jquery. Using the jquery attr() method to get or set the id attribute value of an element. The attr() method sets or returns attribute values of the selected elements.

So, let's see get the id of clicked element jquery, jquery get the id of element, set the id of element jquery, attr method in jquery, how to get the id of the element in javascript, get id of element on click jquery, set attr value jquery.

The following example will display the ID of the DIV element in an alert box on a button click.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>How To Get The ID Of An Element Using jQuery - Websolutionstuff</title>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <style>
            div{
                padding: 20px;
                background: #abb1b8;
            }
        </style>
        <script>
        $(document).ready(function(){
            $("#btnID").click(function(){
                var elmId = $("#divID").attr("id");
                alert(elmId);
            });
        });
        </script>
    </head>
    <body>
        <div id="divID">#text</div><br>
        <button type="button" id="btnID">Show Div ID</button>
    </body>
</html>

You can also get the ID of multiple elements having the same class through the loop, like this.

<!DOCTYPE html>
<html lang="en">
    <head>
    <title>How To Get The ID Of An Element Using jQuery - Websolutionstuff</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <style>
        div{
            padding: 20px;
            margin-bottom: 10px;
            background: #abb1b8;
        }
    </style>
    <script>
    $(document).ready(function(){
        $("#btnID").click(function(){
            var idArr = [];
            $(".box").each(function(){
                idArr.push($(this).attr("id"));
            });
            
            // Join array elements and display in alert
            alert(idArr.join(", "));
        });
    });
    </script>
    </head>
    <body>
        <div class="box" id="divIDOne">#boxOne</div>
        <div class="box" id="divIDTwo">#boxTwo</div>
        <div class="box" id="divIDThree">#boxThree</div>
        <button type="button" id="btnID">Show ID List</button>
    </body>
</html>

Original article source at: https://websolutionstuff.com/

#jquery #element #id 

Get The ID Of An Element Using jQuery
田辺  桃子

田辺 桃子

1681517220

如何在 AngularJS 中使用 anchorScroll 服务滚动到给定元素

AngularJS 中的 anchorScroll 服务允许我们跳转到网页中特定的 HTML 元素。调用它时,它会在 URL 上添加 [#element-id],您可以使用更多代码行将其删除。

它依赖$location服务对 URL 上的 id 进行哈希处理,anchorScroll 读取哈希字符串并在网页中查找给定的 id 并跳转到它。

1.HTML

创建两个按钮 - 一个在顶部,另一个在底部。ng-click在按钮上附加指令并定义navElement()将元素 id 作为参数的函数。

完成代码

<body ng-app='myapp'>
<div ng-controller='contentCtrl'>
<button ng-click='navElement("bottom")' id='top'>Take to bottom</button>

<!-- Content (start) -->
<h1>I'm doing mental jumping jacks.</h1>
<p>Hello, Dexter Morgan. You all right, Dexter? I'm really more an apartment person. Tell him time is of the essence. Finding a needle in a haystack isn't hard when every straw is computerized.</p>
<p>I'm not the monster he wants me to be. So I'm neither man nor beast. I'm something new entirely. With my own set of rules. I'm Dexter. <strong> Boo.</strong> <em> I'm generally confused most of the time.</em> Keep your mind limber.</p>
<h2>Cops, another community I'm not part of.</h2>
<p>I'm real proud of you for coming, bro. I know you hate funerals. You're a killer. I catch killers. Tonight's the night. And it's going to happen again and again. It has to happen. I'm partial to air conditioning.</p>
<ol>
<li>I'm really more an apartment person.</li><li>Only you could make those words cute.</li><li>I'm partial to air conditioning.</li>
</ol>

<h3>I've lived in darkness a long time. Over the years my eyes adjusted until the dark became my world and I could see.</h3>
<p>Makes me a ... scientist. Keep your mind limber. Hello, Dexter Morgan. Only you could make those words cute. Makes me a ... scientist.</p>
<ul>
<li>You're a killer. I catch killers.</li><li>I'm really more an apartment person.</li><li>Under normal circumstances, I'd take that as a compliment.</li>
</ul>

<p>I'm thinking two circus clowns dancing. You? You all right, Dexter? Tell him time is of the essence. I've lived in darkness a long time. Over the years my eyes adjusted until the dark became my world and I could see.</p>
<p>Watching ice melt. This is fun. I think he's got a crush on you, Dex! Makes me a ... scientist. You're a killer. I catch killers. God created pudding, and then he rested. I am not a killer.</p>
<p>I'm going to tell you something that I've never told anyone before. I'm really more an apartment person. Tell him time is of the essence. I'm Dexter, and I'm not sure what I am. Rorschach would say you have a hard time relating to others.</p>
<p>You're a killer. I catch killers. I'm a sociopath; there's not much he can do for me. Keep your mind limber. Makes me a ... scientist.</p>
<p>I feel like a jigsaw puzzle missing a piece. And I'm not even sure what the picture should be. I've lived in darkness a long time. Over the years my eyes adjusted until the dark became my world and I could see.</p>
<p>Makes me a ... scientist. I'm real proud of you for coming, bro. I know you hate funerals. I'm generally confused most of the time. I have a dark side, too.</p>
<p>Tonight's the night. And it's going to happen again and again. It has to happen. This man is a knight in shining armor. Hello, Dexter Morgan. I will not kill my sister. I will not kill my sister. I will not kill my sister.</p>
<p>I'm not the monster he wants me to be. So I'm neither man nor beast. I'm something new entirely. With my own set of rules. I'm Dexter. Boo. I've lived in darkness a long time. Over the years my eyes adjusted until the dark became my world and I could see.</p>
<!-- Content (end) -->

<button ng-click='navElement("top")' id='bottom'>Take to top</button>
</div>
 
</body>

2.脚本

在控制器中$scope也通过$location$anchorScroll。创建一个navElement()以元素 id 作为参数的函数。

$location.hash在页面 URL 上追加元素 ID,例如#bottom。读取anchorScroll()页面 URL 并滚动到定义的哈希 ID。

完成代码

var app = angular.module('myapp', []);
app.controller('contentCtrl', ['$scope', '$location', '$anchorScroll',
 function($scope, $location, $anchorScroll) {
   $scope.navElement = function(elementid) {
    // set the location.hash
    $location.hash(elementid);
 
    $anchorScroll();
  };
 }
]);

3.删除哈希(#)

只需在调用后添加以下两行$anchorScroll()-

// Remove hash
$location.hash('');
$location.replace();

完成代码

var app = angular.module('myapp', []);
app.controller('contentCtrl', ['$scope', '$location', '$anchorScroll',
 function($scope, $location, $anchorScroll) {
   $scope.navElement = function(elementid) {
    // set the location.hash
    $location.hash(elementid);
 
    $anchorScroll();

    // Remove hash
    $location.hash('');
    $location.replace();
  };
 }
]);

4.演示

单击按钮。在新标签页中打开。


5.结论

$location服务用于使用方法在页面 URL 处附加元素 id hash(),并跳转$anchorScroll()到 id。

文章原文出处:https: //makitweb.com/

#angularjs #element 

如何在 AngularJS 中使用 anchorScroll 服务滚动到给定元素
Bongani  Ngema

Bongani Ngema

1681488240

How to Scroll To Given Element with anchorScroll Service in AngularJS

The anchorScroll service in AngularJS allows us to jump to the specific HTML element in the web page. When this gets called then it adds [#element-id] on the URL which you can remove with few more line of code.

It has the dependency on $location service for hash the id on the URL and the anchorScroll reads the hashed string and looks for the given id in the web page and jump to it.

1. HTML

Create two buttons – one at the top and another at the bottom. Attach ng-click directive on the buttons and define navElement() function which takes the element id as a parameter.

Completed Code

<body ng-app='myapp'>
<div ng-controller='contentCtrl'>
<button ng-click='navElement("bottom")' id='top'>Take to bottom</button>

<!-- Content (start) -->
<h1>I'm doing mental jumping jacks.</h1>
<p>Hello, Dexter Morgan. You all right, Dexter? I'm really more an apartment person. Tell him time is of the essence. Finding a needle in a haystack isn't hard when every straw is computerized.</p>
<p>I'm not the monster he wants me to be. So I'm neither man nor beast. I'm something new entirely. With my own set of rules. I'm Dexter. <strong> Boo.</strong> <em> I'm generally confused most of the time.</em> Keep your mind limber.</p>
<h2>Cops, another community I'm not part of.</h2>
<p>I'm real proud of you for coming, bro. I know you hate funerals. You're a killer. I catch killers. Tonight's the night. And it's going to happen again and again. It has to happen. I'm partial to air conditioning.</p>
<ol>
<li>I'm really more an apartment person.</li><li>Only you could make those words cute.</li><li>I'm partial to air conditioning.</li>
</ol>

<h3>I've lived in darkness a long time. Over the years my eyes adjusted until the dark became my world and I could see.</h3>
<p>Makes me a ... scientist. Keep your mind limber. Hello, Dexter Morgan. Only you could make those words cute. Makes me a ... scientist.</p>
<ul>
<li>You're a killer. I catch killers.</li><li>I'm really more an apartment person.</li><li>Under normal circumstances, I'd take that as a compliment.</li>
</ul>

<p>I'm thinking two circus clowns dancing. You? You all right, Dexter? Tell him time is of the essence. I've lived in darkness a long time. Over the years my eyes adjusted until the dark became my world and I could see.</p>
<p>Watching ice melt. This is fun. I think he's got a crush on you, Dex! Makes me a ... scientist. You're a killer. I catch killers. God created pudding, and then he rested. I am not a killer.</p>
<p>I'm going to tell you something that I've never told anyone before. I'm really more an apartment person. Tell him time is of the essence. I'm Dexter, and I'm not sure what I am. Rorschach would say you have a hard time relating to others.</p>
<p>You're a killer. I catch killers. I'm a sociopath; there's not much he can do for me. Keep your mind limber. Makes me a ... scientist.</p>
<p>I feel like a jigsaw puzzle missing a piece. And I'm not even sure what the picture should be. I've lived in darkness a long time. Over the years my eyes adjusted until the dark became my world and I could see.</p>
<p>Makes me a ... scientist. I'm real proud of you for coming, bro. I know you hate funerals. I'm generally confused most of the time. I have a dark side, too.</p>
<p>Tonight's the night. And it's going to happen again and again. It has to happen. This man is a knight in shining armor. Hello, Dexter Morgan. I will not kill my sister. I will not kill my sister. I will not kill my sister.</p>
<p>I'm not the monster he wants me to be. So I'm neither man nor beast. I'm something new entirely. With my own set of rules. I'm Dexter. Boo. I've lived in darkness a long time. Over the years my eyes adjusted until the dark became my world and I could see.</p>
<!-- Content (end) -->

<button ng-click='navElement("top")' id='bottom'>Take to top</button>
</div>
 
</body>

2. Script

In the controller with $scope also pass $location and $anchorScroll. Create a navElement() function that takes element id as parameter.

With $location.hash append element id on the page URL e.g. #bottom. The anchorScroll() read the page URL and scroll to defined hash id.

Completed Code

var app = angular.module('myapp', []);
app.controller('contentCtrl', ['$scope', '$location', '$anchorScroll',
 function($scope, $location, $anchorScroll) {
   $scope.navElement = function(elementid) {
    // set the location.hash
    $location.hash(elementid);
 
    $anchorScroll();
  };
 }
]);

3. Remove Hash(#)

Just add following two lines after calling $anchorScroll()

// Remove hash
$location.hash('');
$location.replace();

Completed Code

var app = angular.module('myapp', []);
app.controller('contentCtrl', ['$scope', '$location', '$anchorScroll',
 function($scope, $location, $anchorScroll) {
   $scope.navElement = function(elementid) {
    // set the location.hash
    $location.hash(elementid);
 
    $anchorScroll();

    // Remove hash
    $location.hash('');
    $location.replace();
  };
 }
]);

4. Demo

Click on the buttons. Open in a new tab.


5. Conclusion

The $location service is used to append element id at the page URL with the hash() method and with the $anchorScroll() jump to the id.

Original article source at: https://makitweb.com/

#angularjs #element 

How to Scroll To Given Element with anchorScroll Service in AngularJS

Проверьте, скрыт или виден элемент с помощью JavaScript

В JavaScript самый быстрый способ проверить, является ли элемент скрытым или видимым в DOM, — это использовать метод getComputedStyle() . Этот метод возвращает фактические значения свойств CSS , используемых для отображения элемента HTML в модели DOM.

Допустим, у нас есть следующий скрытый элемент HTML:

.hidden {
    display: none;
}
<button class="hidden">Click Me!</button>

Элемент HTML может быть скрыт из-за свойств CSS display:none или visible:hidden .

Давайте напишем функцию, которая проверяет оба этих свойства и возвращает логическое значение, отображающее статус видимости элемента:

const isHidden = elem => {
  const styles = window.getComputedStyle(elem)
  return styles.display === 'none' || styles.visibility === 'hidden'
}

const elem = document.querySelector('button')
if (isHidden(elem)) {
  console.log(`Element is hidden!!`)
} else {
  console.log(`Element is visible!!`)
}
// Element is hidden!!

Если вы используете jQuery, вы можете использовать селекторы :hidden и :visible , чтобы проверить, является ли элемент DOM скрытым или видимым:

// Check if element is hidden
if ($('button').is(':hidden')) {
  console.log(`Element is hidden!!`)
}

// Check if element is visible
if ($('button').is(':visible')) {
  console.log(`Element is visible!!`)
}

Оригинальный источник статьи: https://attacomsian.com/

#javascript #element #hidden #visible 

Проверьте, скрыт или виден элемент с помощью JavaScript
田辺  桃子

田辺 桃子

1681462800

使用 JavaScript 检查元素是隐藏还是可见

在 JavaScript 中,检查元素在 DOM 中是隐藏还是可见的最快方法是使用getComputedStyle()方法。此方法返回用于在 DOM 中呈现 HTML 元素的 CSS 属性的实际值。

假设我们有以下隐藏的 HTML 元素:

.hidden {
    display: none;
}
<button class="hidden">Click Me!</button>

由于display:nonevisibility:hidden CSS 属性,HTML 元素可能会被隐藏。

让我们编写一个函数来检查这两个属性并返回一个描述元素可见性状态的布尔值:

const isHidden = elem => {
  const styles = window.getComputedStyle(elem)
  return styles.display === 'none' || styles.visibility === 'hidden'
}

const elem = document.querySelector('button')
if (isHidden(elem)) {
  console.log(`Element is hidden!!`)
} else {
  console.log(`Element is visible!!`)
}
// Element is hidden!!

如果您使用的是 jQuery,则可以使用:hidden:visible选择器来检查DOM 元素是隐藏还是可见:

// Check if element is hidden
if ($('button').is(':hidden')) {
  console.log(`Element is hidden!!`)
}

// Check if element is visible
if ($('button').is(':visible')) {
  console.log(`Element is visible!!`)
}

文章原文出处:https: //attacomsian.com/

#javascript #element #hidden #visible 

使用 JavaScript 检查元素是隐藏还是可见

Check If an Element is Hidden Or Visible using JavaScript

In JavaScript, the quickest way to check if an element is hidden or visible in DOM is to use the getComputedStyle() method. This method returns the actual values of CSS properties used to render an HTML element in DOM.

Let us say that we have got the following hidden HTML element:

.hidden {
    display: none;
}
<button class="hidden">Click Me!</button>

An HTML element can be hidden due to either display:none or visibility:hidden CSS properties.

Let us write a function that checks both these properties and returns a boolean value depicting the visibility status of the element:

const isHidden = elem => {
  const styles = window.getComputedStyle(elem)
  return styles.display === 'none' || styles.visibility === 'hidden'
}

const elem = document.querySelector('button')
if (isHidden(elem)) {
  console.log(`Element is hidden!!`)
} else {
  console.log(`Element is visible!!`)
}
// Element is hidden!!

If you are using jQuery, you can use the :hidden and :visible selectors to check if a DOM element is hidden or visible:

// Check if element is hidden
if ($('button').is(':hidden')) {
  console.log(`Element is hidden!!`)
}

// Check if element is visible
if ($('button').is(':visible')) {
  console.log(`Element is visible!!`)
}

Original article source at: https://attacomsian.com/

#javascript #element #hidden #visible 

Check If an Element is Hidden Or Visible using JavaScript

Получить элемент по атрибуту данных в jQuery

В этой статье мы увидим, как находить элементы на основе значения атрибута данных . Вы можете использовать селекторы атрибутов CSS, чтобы найти элемент HTML на основе его значения атрибута данных с помощью jQuery. Селектор используется для выбора элементов с указанным атрибутом. Мы можем использовать селектор CSS  Attribute , чтобы получить элемент.

Итак, давайте посмотрим, как jquery находит значение атрибута данных, а jquery получает элемент по атрибуту.

Пример: как получить элемент по атрибуту данных в jQuery

<!DOCTYPE html>
<html lang="en">
<head>
<title>How To Get Element By Data Attribute In jQuery - Websolutionstuff</title>
<style>
    ul li { 
        float: left;
        margin: 10px;
        list-style: none;
    }
    ul li img.selected{
        outline: 5px solid black;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("select").change(function(){

        var slide = $(this).children("option:selected").val();
                
        $(".slides img").removeClass("selected");
                
        $('.slides img[data-slide=' + slide + ']').addClass("selected");
    });    
});
</script>
</head>
<body>
    <label>Slide</label>
    <select>
        <option>select</option>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
    </select>
    <hr>
    <ul class="slides">
        <li>
            <img src="images/laravel.jpg" alt="Laravel" data-slide="1">
        </li>
        <li>
            <img src="images/jquery.jpg" alt="jQuery" data-slide="2">
        </li>
        <li>
            <img src="images/php.jpg" alt="PHP" data-slide="3">
        </li>
        <li>
            <img src="images/html.jpg" alt="HTML" data-slide="4">
        </li>
    </ul>
</body>
</html>

Оригинальный источник статьи: https://websolutionstuff.com/

#jquery #element 

Получить элемент по атрибуту данных в jQuery