Javascript this attr src

.attr()

Получает/устанавливает значение атрибутов выбранных элементов.

version added: 1.0 .attr( attributeName )

version added: 1.0 .attr( attributeName, value )

version added: 1.0 .attr( attributes )

version added: 1.1 .attr( attributeName, function(index, attr) )

Метод.attr() достаёт значение атрибута первого элемента, который ему встретится. Для того чтобы получить значение каждого из элементов, нужно воспользоваться такими конструкциями как .each() или .map().

Начиная с jQuery 1.6, метод .attr() возвращает undefined для тех атрибутов, значение которых не было задано. Для получения и выставления таких опций как checked, selected, или disabled используйте метод .prop().

Примеры

Пример: отобразить состояние элемента формы.

    p < margin: 20px 0 0 >b        

Пример: достать атрибут title первого элемента

    em < color:blue; font-weight:bold; >div    

Once there was a large dinosaur.

The title of the emphasis is:

Предположим, у нас есть следующее изображение:

Задаём один атрибут

Для задачи значения атрибуту, в качестве первого аргумента передаём имя, в качестве второго, значение:

$('#greatphoto').attr('alt', 'Beijing Brush Seller');
$('#greatphoto') .attr('title', 'Photo by Kelly Clark');

Задаём сразу несколько атрибутов

Для смены и выставления значения сразу нескольких атрибутов, передадим простой JavaScript объект вида ключ:значение. Каждый ключ — это атрибут:

В этом случае имена атрибутов брать в кавычки не обязательно

Предупреждение: при работе с атрибутом ‘class’, его имя нужно взять в кавычки!

Заметка: jQuery не позволит изменить значение атрибута type элементов или , выкинет ошибку. Дело в том, что атрибут type не можут быть изменён в Internet Explorer.

Динамическое формирование значения атрибутов

С помощью функции, мы можем сформировать динамическое значение атрибута, используя уже существующие значения. К примеру, расширим существующее значение атрибута title:

$('#greatphoto').attr('title', function(i, val) < return val + ' - photo by Kelly Clark' >);

Это может быть полезно для изменения атрибутов сразу большого числа элементов.

Примеры

Пример: Задаём атрибуты всем элементам на странице.

    img < padding:10px; >div      
Attribute of Ajax

Пример: задаём id элементам div, в зависимости от их расположения на странице

    div < color:blue; >span < color:red; >b   
Zero-th
First
Second

Пример: Задаём значение атрибута src, в зависимости от значения атрибута title.

          

Связанные уроки:

Манипулирование атрибутами элементов в jQuery

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

Шпаргалка jQuery:

  • Ajax
    • Global Ajax Event Handlers
      • .ajaxComplete()
        • :button
        • :checkbox
        • :checked
        • :disabled
        • :enabled
        • :file
        • :focus
        • :image
        • .serializeArray()
        • .serialize()
        • jQuery.param()
        • jQuery.ajax()
        • jQuery.ajaxSetup()
        • jQuery.ajaxPrefilter()
        • jQuery.ajaxTransport()
        • jQuery.get()
        • jQuery.post()
        • .load()
        • jQuery.getJSON()
        • jQuery.getScript()
        • .serialize()
        • .serializeArray()
        • jQuery.param()
        • .val()
        • .blur()
        • .change()
        • .focus()
        • .addClass()
        • .hasClass()
        • .removeClass()
        • .toggleClass()
        • .html()
        • .removeAttr()
        • .prop()
        • .removeProp()
        • .attr()
        • .val()
        • Collection Manipulation
          • jQuery.param()
          • .data()
          • .removeData()
          • Class Attribute
            • .addClass()
            • .hasClass()
            • .removeClass()
            • .toggleClass()
            • .clone()
            • .wrap()
            • .wrapAll()
            • .wrapInner()
            • .unwrap()
            • .append()
            • .appendTo()
            • .html()
            • .text()
            • .prepend()
            • .prependTo()
            • .after()
            • .before()
            • .insertAfter()
            • .insertBefore()
            • .unwrap()
            • .remove()
            • .empty()
            • .detach()
            • .replaceAll()
            • .replaceWith()
            • .removeProp()
            • .removeAttr()
            • .prop()
            • .attr()
            • .val()
            • .css()
            • .height()
            • .width()
            • .innerHeight()
            • .innerWidth()
            • .outerHeight()
            • .outerWidth()
            • .offset()
            • .position()
            • .scrollLeft()
            • .scrollTop()
            • .height()
            • .width()
            • .innerHeight()
            • .innerWidth()
            • .outerHeight()
            • .outerWidth()
            • jQuery.holdReady()
            • jQuery()
            • jQuery.noConflict()
            • jQuery.when()
            • .addClass()
            • .hasClass()
            • .removeClass()
            • .toggleClass()
            • .css()
            • .height()
            • .width()
            • .innerHeight()
            • .innerWidth()
            • .outerHeight()
            • .outerWidth()
            • .offset()
            • .position()
            • .scrollLeft()
            • .scrollTop()
            • .clearQueue()
            • .dequeue()
            • .data()
            • jQuery.hasData()
            • jQuery.removeData()
            • jQuery.dequeue()
            • .removeData()
            • jQuery.data()
            • .queue()
            • Custom
              • .clearQueue()
              • .dequeue()
              • .queue()
              • .clearQueue()
              • .dequeue()
              • jQuery.dequeue()
              • jQuery.data()
              • .queue()
              • jQuery.proxy()
              • callbacks.add()
              • callbacks.disable()
              • callbacks.disabled()
              • callbacks.empty()
              • callbacks.fire()
              • callbacks.fired()
              • callbacks.fireWith()
              • callbacks.has()
              • callbacks.lock()
              • callbacks.locked()
              • callbacks.remove()
              • jQuery.Callbacks()
              • deferred.always()
              • deferred.done()
              • deferred.fail()
              • deferred.notify()
              • deferred.notifyWith()
              • deferred.progress()
              • deferred.promise()
              • deferred.reject()
              • deferred.rejectWith()
              • deferred.resolve()
              • deferred.resolveWith()
              • deferred.state()
              • deferred.then()
              • Basics
                • Универсальный селектор (“*”)
                • jQuery( «.class» )
                • Селектор элементов (“element”)
                • Селектор ID (“#id”)
                • Множественный (“selector1, selector2, selectorN”)
                • Селектор по префиксу [name|=”value”]
                • Селектор содержащий значение [name*=»value»]
                • Селектор, содержащий слово [name~=»value»]
                • Селектор по атрибуту, на конце которого [name$=»value»]
                • Селектор по равенству [name=»value»]
                • Селектор по неравенству [name!=»value»]
                • Значение атрибута начинается с [name^=»value»]
                • Селектор по наличию атрибута [name]
                • Множественный селектор по атрибуту [name=»value»][name2=»value2″]
                • :animated Selector
                • :eq()
                • :even
                • :first
                • :focus
                • :gt()
                • :header
                • :lang()
                • :last
                • :lt()
                • :first-child
                • :first-of-type
                • :last-child
                • :last-of-type
                • :nth-child()
                • :nth-last-child()
                • :nth-last-of-type()
                • :nth-of-type()
                • :only-child
                • :only-of-type
                • :contains()
                • :empty
                • :has()
                • :parent
                • Browser Events
                  • .resize()
                  • .scroll()
                  • .ready()
                  • .bind()
                  • .delegate()
                  • jQuery.proxy()
                  • .off()
                  • .one()
                  • .trigger()
                  • .triggerHandler()
                  • .unbind()
                  • .undelegate()
                  • event.currentTarget
                  • event.data
                  • event.delegateTarget
                  • event.isDefaultPrevented()
                  • event.isImmediatePropagationStopped()
                  • event.isPropagationStopped()
                  • event.metaKey
                  • event.namespace
                  • event.pageX
                  • event.pageY
                  • event.preventDefault()
                  • event.relatedTarget
                  • event.result
                  • event.stopImmediatePropagation()
                  • event.stopPropagation()
                  • event.target
                  • event.timeStamp
                  • event.type
                  • event.which
                  • .blur()
                  • .change()
                  • .focus()
                  • .focusin()

                  Источник

                  .attr()

                  Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

                  Contents:

                  .attr( attributeName ) Returns: String

                  Description: Get the value of an attribute for the first element in the set of matched elements.

                  version added: 1.0 .attr( attributeName )

                  The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery’s .each() or .map() method.

                  Using jQuery’s .attr() method to get the value of an element’s attribute has two main benefits:

                  1. Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
                  2. Cross-browser consistency: The values of some attributes are reported inconsistently across browsers, and even across versions of a single browser. The .attr() method reduces such inconsistencies.

                  Note: Attribute values are strings with the exception of a few attributes such as value and tabindex.

                  As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked , selected , or disabled state of form elements, use the .prop() method.

                  Attributes vs. Properties

                  The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

                  For example, selectedIndex , tagName , nodeName , nodeType , ownerDocument , defaultChecked , and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr . These do not have corresponding attributes and are only properties.

                  Concerning boolean attributes, consider a DOM element defined by the HTML markup , and assume it is in a JavaScript variable named elem :

                  elem.checked true (Boolean) Will change with checkbox state
                  $( elem ).prop( «checked» ) true (Boolean) Will change with checkbox state
                  elem.getAttribute( «checked» ) «checked» (String) Initial state of the checkbox; does not change
                  $( elem ).attr( «checked» ) (1.6+) «checked» (String) Initial state of the checkbox; does not change
                  $( elem ).attr( «checked» ) (pre-1.6) true (Boolean) Changed with checkbox state

                  According to the W3C forms specification, the checked attribute is a boolean attribute, which means the corresponding property is true if the attribute is present at all—even if, for example, the attribute has no value or is set to empty string value or even «false». This is true of all boolean attributes.

                  Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property:

                  The same is true for other dynamic attributes, such as selected and value .

                  Additional Notes:

                  • In Internet Explorer prior to version 9, using .prop() to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp() ) before the DOM element is removed from the document. To safely set values on DOM objects without memory leaks, use .data() .

                  Examples:

                  Display the checked attribute and property of a checkbox as it changes.

                  Источник

                  Читайте также:  Keyframes css при наведении
Оцените статью